Skip to content

[Routing] Allow defining and reusing subroutines #26529

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

Closed
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,11 @@ final public function collection($name = '')
{
return new CollectionConfigurator($this->collection, $name);
}

final public function subroutine(string $name, string $pattern): self
{
$this->collection->setSubroutine($name, $pattern);

return $this;
}
}
3 changes: 3 additions & 0 deletions src/Symfony/Component/Routing/Loader/XmlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ protected function parseNode(RouteCollection $collection, \DOMElement $node, $pa
case 'import':
$this->parseImport($collection, $node, $path, $file);
break;
case 'subroutine':
$collection->setSubroutine($node->getAttribute('id'), $node->getAttribute('pattern'));
break;
default:
throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "route" or "import".', $node->localName, $path));
}
Expand Down
6 changes: 6 additions & 0 deletions src/Symfony/Component/Routing/Loader/YamlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ public function load($file, $type = null)
}

foreach ($parsedConfig as $name => $config) {
if ('_subroutines' === $name && \is_array($config) && !isset($config['resource']) && !isset($config['path'])) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why check against for resource and path ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for BC

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we trigger a deprecation if somebody tries to use _subroutines as a route name here?

foreach ($config as $name => $pattern) {
$collection->setSubroutine($name, $pattern);
}
continue;
}
$this->validate($config, $name, $path);

if (isset($config['resource'])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element name="import" type="import" />
<xsd:element name="route" type="route" />
<xsd:element name="subroutine" type="subroutine" />
</xsd:choice>
</xsd:complexType>

Expand Down Expand Up @@ -69,6 +70,11 @@
<xsd:attribute name="controller" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="subroutine">
<xsd:attribute name="id" type="xsd:string" use="required" />
<xsd:attribute name="pattern" type="xsd:string" use="required" />
</xsd:complexType>

<xsd:complexType name="default" mixed="true">
<xsd:choice minOccurs="0" maxOccurs="1">
<xsd:element name="bool" type="xsd:boolean" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ private function compileDynamicRoutes(RouteCollection $collection, bool $matchHo
$code .= "\n .')'";
$state->regex .= ')';
}
foreach ($this->getRoutes()->getSubroutines() as $name => $rx) {
$rx = sprintf('(?(DEFINE)(?P<%s>%s))', $name, $rx);
$code .= "\n .'{$rx}'";
$state->regex .= $rx;
}
$rx = ")$}{$modifiers}";
$code .= "\n .'{$rx}',";
$state->regex .= $rx;
Expand Down
20 changes: 17 additions & 3 deletions src/Symfony/Component/Routing/Matcher/UrlMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ public function addExpressionLanguageProvider(ExpressionFunctionProviderInterfac
*/
protected function matchCollection($pathinfo, RouteCollection $routes)
{
$subroutines = '';
foreach ($routes->getSubroutines() as $name => $pattern) {
$subroutines .= sprintf('(?(DEFINE)(?P<%s>%s))', $name, $pattern);
}

foreach ($routes as $name => $route) {
$compiledRoute = $route->compile();

Expand All @@ -138,13 +143,22 @@ protected function matchCollection($pathinfo, RouteCollection $routes)
continue;
}

if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
$rx = $compiledRoute->getRegex();
if ('' !== $subroutines) {
$rx = substr_replace($rx, $subroutines, strrpos($rx, '#'), 0);
}
if (!preg_match($rx, $pathinfo, $matches)) {
continue;
}

$hostMatches = array();
if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
continue;
if ($rx = $compiledRoute->getHostRegex()) {
if ('' !== $subroutines) {
$rx = substr_replace($rx, $subroutines, strrpos($rx, '#'), 0);
}
if (!preg_match($rx, $this->context->getHost(), $hostMatches)) {
continue;
}
}

$status = $this->handleRouteRequirements($pathinfo, $name, $route);
Expand Down
28 changes: 28 additions & 0 deletions src/Symfony/Component/Routing/RouteCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ class RouteCollection implements \IteratorAggregate, \Countable
*/
private $resources = array();

/**
* @var array
*/
private $subroutines = array();

public function __clone()
{
foreach ($this->routes as $name => $route) {
Expand Down Expand Up @@ -129,6 +134,10 @@ public function addCollection(self $collection)
foreach ($collection->getResources() as $resource) {
$this->addResource($resource);
}

foreach ($collection->getSubroutines() as $name => $pattern) {
$this->setSubroutine($name, $pattern);
}
}

/**
Expand Down Expand Up @@ -291,4 +300,23 @@ public function addResource(ResourceInterface $resource)
$this->resources[$key] = $resource;
}
}

/**
* Sets a subroutine that can be reused in requirements.
*/
public function setSubroutine(string $name, string $pattern)
{
if (\strlen($name) > RouteCompiler::VARIABLE_MAXIMUM_LENGTH) {
throw new \DomainException(sprintf('Subroutine name "%s" cannot be longer than %s characters. Please use a shorter name for pattern "%s".', $name, RouteCompiler::VARIABLE_MAXIMUM_LENGTH, $pattern));
}
$this->subroutines[$name] = $pattern;
}

/**
* Returns the defined subroutines.
*/
public function getSubroutines(): array
{
return $this->subroutines;
}
}
25 changes: 25 additions & 0 deletions src/Symfony/Component/Routing/RouteCollectionBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class RouteCollectionBuilder
private $schemes;
private $methods;
private $resources = array();
private $subroutines = array();

public function __construct(LoaderInterface $loader = null)
{
Expand Down Expand Up @@ -76,6 +77,10 @@ public function import($resource, $prefix = '/', $type = null)
foreach ($collection->getResources() as $resource) {
$builder->addResource($resource);
}

foreach ($collection->getSubroutines() as $name => $pattern) {
$builder->setSubroutine($name, $pattern);
}
}

// mount into this builder
Expand Down Expand Up @@ -262,6 +267,22 @@ private function addResource(ResourceInterface $resource): RouteCollectionBuilde
return $this;
}

/**
* Sets a subroutine that can be reused in requirements.
*/
public function setSubroutine(string $name, string $pattern)
{
$this->subroutines[$name] = $pattern;
}

/**
* Returns the defined subroutines.
*/
public function getSubroutines()
{
return $this->subroutines;
}

/**
* Creates the final RouteCollection and returns it.
*
Expand Down Expand Up @@ -321,6 +342,10 @@ public function build()
$routeCollection->addResource($resource);
}

foreach ($this->subroutines as $name => $pattern) {
$routeCollection->setSubroutine($name, $pattern);
}

return $routeCollection;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
xsi:schemaLocation="http://symfony.com/schema/routing
http://symfony.com/schema/routing/routing-1.0.xsd">

<subroutine id="number" pattern="\d" />

<route id="app_homepage" path="/" controller="AppBundle:Homepage:show" />

<route id="app_blog" path="/blog">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
_subroutines:
number: \d

app_homepage:
path: /
controller: AppBundle:Homepage:show
Expand Down
2 changes: 2 additions & 0 deletions src/Symfony/Component/Routing/Tests/Fixtures/php_dsl.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Symfony\Component\Routing\Loader\Configurator;

return function (RoutingConfigurator $routes) {
$routes->subroutine('number', '\d');

$routes
->collection()
->add('foo', '/foo')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ public function testRoutingConfigurator()
->setMethods(array('GET'))
->setDefaults(array('id' => 0))
);
$expectedCollection->setSubroutine('number', '\d');

$expectedCollection->addResource(new FileResource(realpath(__DIR__.'/../Fixtures/php_dsl_sub.php')));
$expectedCollection->addResource(new FileResource(realpath(__DIR__.'/../Fixtures/php_dsl.php')));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -411,4 +411,12 @@ public function testImportRouteWithNamePrefix()
$this->assertNotNull($routeCollection->get('api_app_blog'));
$this->assertEquals('/api/blog', $routeCollection->get('api_app_blog')->getPath());
}

public function testSubroutine()
{
$loader = new XmlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures/controller')));
$routeCollection = $loader->load('routing.xml');

$this->assertSame(array('number' => '\d'), $routeCollection->getSubroutines());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -275,4 +275,12 @@ public function testImportingWithControllerDefault()
$this->assertEquals('DefaultController::defaultAction', $routes->get('home.nl')->getDefault('_controller'));
$this->assertEquals('DefaultController::defaultAction', $routes->get('not_localized')->getDefault('_controller'));
}

public function testSubroutine()
{
$loader = new YamlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures/controller')));
$routeCollection = $loader->load('routing.yml');

$this->assertSame(array('number' => '\d'), $routeCollection->getSubroutines());
}
}
10 changes: 10 additions & 0 deletions src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,16 @@ public function testRequirementWithCapturingGroup()
$this->assertEquals(array('_route' => 'a', 'a' => 'a', 'b' => 'b'), $matcher->match('/a/b'));
}

public function testSubroutine()
{
$coll = new RouteCollection();
$coll->setSubroutine('date', '\d{4}-\d{2}-\d{2}');
$coll->add('a', new Route('/{a}', array(), array('a' => '(?&date)')));

$matcher = $this->getUrlMatcher($coll);
$this->assertEquals(array('_route' => 'a', 'a' => '2018-03-14'), $matcher->match('/2018-03-14'));
}

protected function getUrlMatcher(RouteCollection $routes, RequestContext $context = null)
{
return new UrlMatcher($routes, $context ?: new RequestContext());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,4 +361,13 @@ public function testAddsThePrefixOnlyOnceWhenLoadingMultipleCollections()
$this->assertEquals('/other/a', $routes['a']->getPath());
$this->assertEquals('/other/b', $routes['b']->getPath());
}

public function testSubroutine()
{
$routeCollectionBuilder = new RouteCollectionBuilder(new YamlFileLoader(new FileLocator(array(__DIR__.'/Fixtures/controller'))));
$routeCollectionBuilder->import('routing.yml');
$routeCollection = $routeCollectionBuilder->build();

$this->assertSame(array('number' => '\d'), $routeCollection->getSubroutines());
}
}