Skip to content

[Router] allow to use \A and \z as regex start and end #37711

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Routing/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
-----

* Added support for inline definition of requirements and defaults for host
* Added support for `\A` and `\z` as regex start and end for route requirement

5.1.0
-----
Expand Down
10 changes: 8 additions & 2 deletions src/Symfony/Component/Routing/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -553,12 +553,18 @@ private function extractInlineDefaultsAndRequirements(string $pattern): string

private function sanitizeRequirement(string $key, string $regex)
{
if ('' !== $regex && '^' === $regex[0]) {
$regex = (string) substr($regex, 1); // returns false for a single character
if ('' !== $regex) {
if ('^' === $regex[0]) {
$regex = substr($regex, 1);
} elseif (0 === strpos($regex, '\\A')) {
$regex = substr($regex, 2);
}
}

if ('$' === substr($regex, -1)) {
$regex = substr($regex, 0, -1);
} elseif (\strlen($regex) - 2 === strpos($regex, '\\z')) {
$regex = substr($regex, 0, -2);
}

if ('' === $regex) {
Expand Down
11 changes: 11 additions & 0 deletions src/Symfony/Component/Routing/Tests/RouteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,14 @@ public function testRequirement()
$this->assertTrue($route->hasRequirement('foo'), '->hasRequirement() return true if requirement is set');
}

public function testRequirementAlternativeStartAndEndRegexSyntax()
{
$route = new Route('/{foo}');
$route->setRequirement('foo', '\A\d+\z');
$this->assertEquals('\d+', $route->getRequirement('foo'), '->setRequirement() removes \A and \z from the path');
$this->assertTrue($route->hasRequirement('foo'));
}

/**
* @dataProvider getInvalidRequirements
*/
Expand All @@ -139,6 +147,9 @@ public function getInvalidRequirements()
['^$'],
['^'],
['$'],
['\A\z'],
['\A'],
['\z'],
];
}

Expand Down