Thanks to visit codestin.com
Credit goes to github.com

Skip to content

UrlGenerator has incorrect scheme-validation #18106

Closed
@arjenm

Description

@arjenm

Hi, I was looking at the code from the UrlGenerator::doGenerate and noticed something odd about the code which validates the scheme.

I.e. this piece of code

            if ($requiredSchemes) {
                $schemeMatched = false;
                foreach ($requiredSchemes as $requiredScheme) {
                    if ($scheme === $requiredScheme) {
                        $schemeMatched = true;
                        break;
                    }
                }
                if (!$schemeMatched) {
                    $referenceType = self::ABSOLUTE_URL;
                    $scheme = current($requiredSchemes);
                }
            }

When the current scheme doesn't match any of the required schemes, it uses current($requiredSchemes);

The foreach moved the pointer of that array past the last element, so current will return false.

See the output of this small test script.

$scheme = 'ftp';
$requiredSchemes = ['http', 'https'];

$schemeMatched = false;
foreach ($requiredSchemes as $requiredScheme) {
  if ($scheme === $requiredScheme) {
    $schemeMatched = true;
    break;
  }
}
if (!$schemeMatched) {
  $scheme = current($requiredSchemes);
}

var_dump($scheme);

This outputs bool(false) rather than string(4) "http"

By the way, the code seems overly complex, this should also work for the intended purpose:

if (!in_array($scheme, $requiredSchemes, true)) {
    $scheme = reset($requiredSchemes); // current would actually work here as well
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions