Skip to content

[Routing] Add support for aliasing routes #38389

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
wants to merge 3 commits into from
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
35 changes: 35 additions & 0 deletions src/Symfony/Component/Routing/Alias.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Routing;

final class Alias
{
/**
* @var string
*/
private $name;

public function __construct(string $name)
{
$this->name = $name;
}

/**
* Returns the name of this alias.
*
* @return string The alias name
*/
public function __toString(): string
{
return $this->name;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ class CompiledUrlGeneratorDumper extends GeneratorDumper
{
public function getCompiledRoutes(): array
{
$routes = $this->getRoutes();
$compiledRoutes = [];
foreach ($this->getRoutes()->all() as $name => $route) {
foreach ($routes->all() as $name => $route) {
$compiledRoute = $route->compile();

$compiledRoutes[$name] = [
Expand All @@ -38,6 +39,10 @@ public function getCompiledRoutes(): array
];
}

foreach ($routes->resolveAliases() as $alias => $target) {
$compiledRoutes[$alias] = $compiledRoutes[$target];
}

return $compiledRoutes;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ final public function collection(string $name = ''): CollectionConfigurator
return new CollectionConfigurator($this->collection, $name);
}

final public function alias(string $name, string $referencedName): void
{
$this->collection->setAlias($name, $referencedName);
}

/**
* @return static
*/
Expand Down
6 changes: 6 additions & 0 deletions src/Symfony/Component/Routing/Loader/XmlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,12 @@ protected function parseRoute(RouteCollection $collection, \DOMElement $node, st
throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must have an "id" attribute.', $path));
}

if ($alias = $node->getAttribute('alias')) {
$collection->setAlias($id, $alias);

return;
}

$schemes = preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, \PREG_SPLIT_NO_EMPTY);
$methods = preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, \PREG_SPLIT_NO_EMPTY);

Expand Down
15 changes: 14 additions & 1 deletion src/Symfony/Component/Routing/Loader/YamlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class YamlFileLoader extends FileLoader
use PrefixTrait;

private static $availableKeys = [
'resource', 'type', 'prefix', 'path', 'host', 'schemes', 'methods', 'defaults', 'requirements', 'options', 'condition', 'controller', 'name_prefix', 'trailing_slash_on_root', 'locale', 'format', 'utf8', 'exclude', 'stateless',
'resource', 'type', 'prefix', 'path', 'host', 'schemes', 'methods', 'defaults', 'requirements', 'options', 'condition', 'controller', 'name_prefix', 'trailing_slash_on_root', 'locale', 'format', 'utf8', 'exclude', 'stateless', 'alias',
];
private $yamlParser;

Expand Down Expand Up @@ -113,6 +113,12 @@ public function supports($resource, string $type = null)
*/
protected function parseRoute(RouteCollection $collection, string $name, array $config, string $path)
{
if (isset($config['alias'])) {
$collection->setAlias($name, $config['alias']);

return;
}

$defaults = isset($config['defaults']) ? $config['defaults'] : [];
$requirements = isset($config['requirements']) ? $config['requirements'] : [];
$options = isset($config['options']) ? $config['options'] : [];
Expand Down Expand Up @@ -243,6 +249,13 @@ protected function validate($config, string $name, string $path)
if ($extraKeys = array_diff(array_keys($config), self::$availableKeys)) {
throw new \InvalidArgumentException(sprintf('The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".', $path, $name, implode('", "', $extraKeys), implode('", "', self::$availableKeys)));
}
if (isset($config['alias'])) {
if (1 === \count($config)) {
// No need to continue, if an alias is set, it's the only desired key
return;
}
throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify other keys than "alias" for "%s".', $path, $name));
}
if (isset($config['resource']) && isset($config['path'])) {
throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "resource" key and the "path" key for "%s". Choose between an import and a route definition.', $path, $name));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
<xsd:attribute name="format" type="xsd:string" />
<xsd:attribute name="utf8" type="xsd:boolean" />
<xsd:attribute name="stateless" type="xsd:boolean" />
<xsd:attribute name="alias" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="import">
Expand Down
86 changes: 83 additions & 3 deletions src/Symfony/Component/Routing/RouteCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
namespace Symfony\Component\Routing;

use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

/**
* A RouteCollection represents a set of Route instances.
Expand All @@ -30,6 +32,11 @@ class RouteCollection implements \IteratorAggregate, \Countable
*/
private $routes = [];

/**
* @var Alias[]
*/
private $aliases = [];

/**
* @var array
*/
Expand All @@ -45,6 +52,10 @@ public function __clone()
foreach ($this->routes as $name => $route) {
$this->routes[$name] = clone $route;
}

foreach ($this->aliases as $alias => $route) {
$this->aliases[$alias] = clone $route;
}
}

/**
Expand Down Expand Up @@ -80,7 +91,7 @@ public function add(string $name, Route $route/*, int $priority = 0*/)
trigger_deprecation('symfony/routing', '5.1', 'The "%s()" method will have a new "int $priority = 0" argument in version 6.0, not defining it is deprecated.', __METHOD__);
}

unset($this->routes[$name], $this->priorities[$name]);
unset($this->routes[$name], $this->priorities[$name], $this->aliases[$name]);

$this->routes[$name] = $route;

Expand Down Expand Up @@ -114,6 +125,10 @@ public function all()
*/
public function get(string $name)
{
if (isset($this->aliases[$name])) {
return $this->get((string) $this->aliases[$name]);
}

return isset($this->routes[$name]) ? $this->routes[$name] : null;
}

Expand All @@ -125,7 +140,7 @@ public function get(string $name)
public function remove($name)
{
foreach ((array) $name as $n) {
unset($this->routes[$n], $this->priorities[$n]);
unset($this->routes[$n], $this->priorities[$n], $this->aliases[$n]);
}
}

Expand All @@ -138,14 +153,18 @@ public function addCollection(self $collection)
// we need to remove all routes with the same names first because just replacing them
// would not place the new route at the end of the merged array
foreach ($collection->all() as $name => $route) {
unset($this->routes[$name], $this->priorities[$name]);
unset($this->routes[$name], $this->priorities[$name], $this->aliases[$name]);
$this->routes[$name] = $route;

if (isset($collection->priorities[$name])) {
$this->priorities[$name] = $collection->priorities[$name];
}
}

foreach ($collection->getAliases() as $alias => $route) {
$this->setAlias($alias, $route);
}

foreach ($collection->getResources() as $resource) {
$this->addResource($resource);
}
Expand Down Expand Up @@ -303,4 +322,65 @@ public function addResource(ResourceInterface $resource)
$this->resources[$key] = $resource;
}
}

/**
* Sets an alias for an existing route.
*
* @param string $alias The alias to create
* @param string|Alias $route The route to alias
*
* @throws InvalidArgumentException if the id is not a string or an Alias
* @throws InvalidArgumentException if the alias is for itself
*/
public function setAlias(string $alias, $route): Alias
{
if (\is_string($route)) {
$route = new Alias($route);
} elseif (!$route instanceof Alias) {
throw new InvalidArgumentException('$route must be a string, or an Alias object.');
}

if ($alias === (string) $route) {
throw new InvalidArgumentException(sprintf('An alias can not reference itself, got a circular reference on "%s".', $alias));
}

unset($this->routes[$alias], $this->priorities[$alias]);

Choose a reason for hiding this comment

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

Add a comment to explain why you unset these keys in these array?


return $this->aliases[$alias] = $route;
}

/**
* @return array<string, Alias>
*/
public function getAliases(): array
{
return $this->aliases;
}

/**
* @return string[] An array of resolved route names
*/
public function resolveAliases(): array
{
$resolvedAliases = [];
foreach ($this->aliases as $alias => $target) {
$resolved = $this->resolveAlias((string) $target);
if (null === $resolved) {
throw new RouteNotFoundException(sprintf('Target route "%s" for alias "%s" is not defined.', $target, $alias));
}

$resolvedAliases[$alias] = $resolved;
}

return $resolvedAliases;
}

private function resolveAlias(string $alias): ?string
{
if (isset($this->aliases[$alias])) {
return $this->resolveAlias((string) $this->aliases[$alias]);
}

return isset($this->routes[$alias]) ? $alias : null;
}
}
12 changes: 12 additions & 0 deletions src/Symfony/Component/Routing/Tests/Fixtures/alias/alias.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

return static function (RoutingConfigurator $routes): void {
$routes->add('route', '/hello');
$routes->add('overrided', '/');
$routes->alias('alias', 'route');
$routes->alias('alias2', 'route');
$routes->alias('deep', 'alias');
$routes->alias('overrided', 'route');
};
13 changes: 13 additions & 0 deletions src/Symfony/Component/Routing/Tests/Fixtures/alias/alias.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing
https://symfony.com/schema/routing/routing-1.0.xsd">

<route id="route" path="/hello"/>
<route id="overrided" path="/"/>
<route id="alias" alias="route"/>
<route id="alias2" alias="route"/>
<route id="deep" alias="alias"/>
<route id="overrided" alias="route"/>
</routes>
12 changes: 12 additions & 0 deletions src/Symfony/Component/Routing/Tests/Fixtures/alias/alias.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
route:
path: /hello
overrided:
path: /
alias:
alias: route
alias2:
alias: route
deep:
alias: alias
_import:
resource: override.yaml
22 changes: 22 additions & 0 deletions src/Symfony/Component/Routing/Tests/Fixtures/alias/expected.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

return static function (string $format) {
$expectedRoutes = new RouteCollection();

$expectedRoutes->add('route', new Route('/hello'));
$expectedRoutes->setAlias('alias', 'route');
$expectedRoutes->setAlias('alias2', 'route');
$expectedRoutes->setAlias('deep', 'alias');
$expectedRoutes->setAlias('overrided', 'route');

$expectedRoutes->addResource(new FileResource(__DIR__."/alias.$format"));
if ($format === 'yaml') {
$expectedRoutes->addResource(new FileResource(__DIR__."/override.$format"));
}

return $expectedRoutes;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
overrided:
alias: route
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
namespace Symfony\Component\Routing\Tests\Generator\Dumper;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Routing\Alias;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Generator\CompiledUrlGenerator;
use Symfony\Component\Routing\Generator\Dumper\CompiledUrlGeneratorDumper;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
Expand Down Expand Up @@ -256,4 +258,31 @@ public function testDumpWithLocalizedRoutesPreserveTheGoodLocaleInTheUrl()
$this->assertSame('/fun', $compiledUrlGenerator->generate('fun', ['_locale' => 'en']));
$this->assertSame('/amusant', $compiledUrlGenerator->generate('fun.fr', ['_locale' => 'en']));
}

public function testAliases()
{
$this->routeCollection->add('a', new Route('/hello'));
$this->routeCollection->setAlias('b', 'a');
$this->routeCollection->setAlias('c', new Alias('b'));

file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump());

$compiledUrlGenerator = new CompiledUrlGenerator(require $this->testTmpFilepath, new RequestContext());

$this->assertSame('/hello', $compiledUrlGenerator->generate('b'));
$this->assertSame('/hello', $compiledUrlGenerator->generate('c'));
}

public function testTargetAliasNotExisting()
{
$this->expectException(RouteNotFoundException::class);

$this->routeCollection->setAlias('a', 'not-existing');

file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump());

$compiledUrlGenerator = new CompiledUrlGenerator(require $this->testTmpFilepath, new RequestContext());

$compiledUrlGenerator->generate('a');
}
}
Loading