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

This commit is contained in:
Zlatoslav Desyatnikov 2020-07-30 19:54:20 +03:00 committed by Fabien Potencier
parent e411c96718
commit f752eeeaa6
3 changed files with 20 additions and 2 deletions

View File

@ -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
-----

View File

@ -553,12 +553,18 @@ class Route implements \Serializable
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) {

View File

@ -122,6 +122,14 @@ class RouteTest extends TestCase
$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
*/
@ -139,6 +147,9 @@ class RouteTest extends TestCase
['^$'],
['^'],
['$'],
['\A\z'],
['\A'],
['\z'],
];
}