Skip to content

[Routing] Add support for aliasing routes #38464

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
merged 1 commit into from
Nov 4, 2021
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
96 changes: 96 additions & 0 deletions src/Symfony/Component/Routing/Alias.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?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;

use Symfony\Component\Routing\Exception\InvalidArgumentException;

class Alias
{
private $id;
private $deprecation = [];

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

/**
* @return static
*/
public function withId(string $id): self
{
$new = clone $this;

$new->id = $id;

return $new;
}

/**
* Returns the target name of this alias.
*
* @return string The target name
*/
public function getId(): string
{
return $this->id;
}

/**
* Whether this alias is deprecated, that means it should not be referenced anymore.
*
* @param string $package The name of the composer package that is triggering the deprecation
* @param string $version The version of the package that introduced the deprecation
* @param string $message The deprecation message to use
*
* @return $this
*
* @throws InvalidArgumentException when the message template is invalid
*/
public function setDeprecated(string $package, string $version, string $message): self
{
if ('' !== $message) {
if (preg_match('#[\r\n]|\*/#', $message)) {
throw new InvalidArgumentException('Invalid characters found in deprecation template.');
}

if (!str_contains($message, '%alias_id%')) {
throw new InvalidArgumentException('The deprecation template must contain the "%alias_id%" placeholder.');
}
}

$this->deprecation = [
'package' => $package,
'version' => $version,
'message' => $message ?: 'The "%alias_id%" route alias is deprecated. You should stop using it, as it will be removed in the future.',
];

return $this;
}

public function isDeprecated(): bool
{
return (bool) $this->deprecation;
}

/**
* @param string $name Route name relying on this alias
*/
public function getDeprecation(string $name): array
{
return [
'package' => $this->deprecation['package'],
'version' => $this->deprecation['version'],
'message' => str_replace('%alias_id%', $name, $this->deprecation['message']),
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?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\Exception;

class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?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\Exception;

class RouteCircularReferenceException extends RuntimeException
{
public function __construct(string $routeId, array $path)
{
parent::__construct(sprintf('Circular reference detected for route "%s", path: "%s".', $routeId, implode(' -> ', $path)));
}
}
16 changes: 16 additions & 0 deletions src/Symfony/Component/Routing/Exception/RuntimeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?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\Exception;

class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ public function generate(string $name, array $parameters = [], int $referenceTyp
throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
}

[$variables, $defaults, $requirements, $tokens, $hostTokens, $requiredSchemes] = $this->compiledRoutes[$name];
[$variables, $defaults, $requirements, $tokens, $hostTokens, $requiredSchemes, $deprecations] = $this->compiledRoutes[$name] + [6 => []];

foreach ($deprecations as $deprecation) {
trigger_deprecation($deprecation['package'], $deprecation['version'], $deprecation['message']);
}

if (isset($defaults['_canonical_route']) && isset($defaults['_locale'])) {
if (!\in_array('_locale', $variables, true)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\Routing\Generator\Dumper;

use Symfony\Component\Routing\Exception\RouteCircularReferenceException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper;

/**
Expand All @@ -35,12 +37,57 @@ public function getCompiledRoutes(): array
$compiledRoute->getTokens(),
$compiledRoute->getHostTokens(),
$route->getSchemes(),
[],
];
}

return $compiledRoutes;
}

public function getCompiledAliases(): array
{
$routes = $this->getRoutes();
$compiledAliases = [];
foreach ($routes->getAliases() as $name => $alias) {
$deprecations = $alias->isDeprecated() ? [$alias->getDeprecation($name)] : [];
$currentId = $alias->getId();
$visited = [];
while (null !== $alias = $routes->getAlias($currentId) ?? null) {
if (false !== $searchKey = array_search($currentId, $visited)) {
$visited[] = $currentId;

throw new RouteCircularReferenceException($currentId, \array_slice($visited, $searchKey));
}

if ($alias->isDeprecated()) {
$deprecations[] = $deprecation = $alias->getDeprecation($currentId);
trigger_deprecation($deprecation['package'], $deprecation['version'], $deprecation['message']);
Copy link
Member

Choose a reason for hiding this comment

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

targeting a deprecated alias should raise a deprecation, so this one is fine compared to the previous one

}

$visited[] = $currentId;
$currentId = $alias->getId();
}

if (null === $target = $routes->get($currentId)) {
throw new RouteNotFoundException(sprintf('Target route "%s" for alias "%s" does not exist.', $currentId, $name));
}

$compiledTarget = $target->compile();

$compiledAliases[$name] = [
$compiledTarget->getVariables(),
$target->getDefaults(),
$target->getRequirements(),
$compiledTarget->getTokens(),
$compiledTarget->getHostTokens(),
$target->getSchemes(),
$deprecations,
];
}

return $compiledAliases;
}

/**
* {@inheritdoc}
*/
Expand Down Expand Up @@ -68,6 +115,10 @@ private function generateDeclaredRoutes(): string
$routes .= sprintf("\n '%s' => %s,", $name, CompiledUrlMatcherDumper::export($properties));
}

foreach ($this->getCompiledAliases() as $alias => $properties) {
$routes .= sprintf("\n '%s' => %s,", $alias, CompiledUrlMatcherDumper::export($properties));
}

return $routes;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?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\Loader\Configurator;

use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\Routing\Alias;

class AliasConfigurator
{
private $alias;

public function __construct(Alias $alias)
{
$this->alias = $alias;
}

/**
* Whether this alias is deprecated, that means it should not be called anymore.
*
* @param string $package The name of the composer package that is triggering the deprecation
* @param string $version The version of the package that introduced the deprecation
* @param string $message The deprecation message to use
*
* @return $this
*
* @throws InvalidArgumentException when the message template is invalid
*/
public function deprecate(string $package, string $version, string $message): self
{
$this->alias->setDeprecated($package, $version, $message);

return $this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\Routing\Loader\Configurator\Traits;

use Symfony\Component\Routing\Loader\Configurator\AliasConfigurator;
use Symfony\Component\Routing\Loader\Configurator\CollectionConfigurator;
use Symfony\Component\Routing\Loader\Configurator\RouteConfigurator;
use Symfony\Component\Routing\RouteCollection;
Expand Down Expand Up @@ -42,6 +43,11 @@ public function add(string $name, $path): RouteConfigurator
return new RouteConfigurator($this->collection, $route, $this->name, $parentConfigurator, $this->prefixes);
}

public function alias(string $name, string $alias): AliasConfigurator
{
return new AliasConfigurator($this->collection->addAlias($name, $alias));
}

/**
* Adds a route.
*
Expand Down
47 changes: 47 additions & 0 deletions src/Symfony/Component/Routing/Loader/XmlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,16 @@ 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')) {
$alias = $collection->addAlias($id, $alias);

if ($deprecationInfo = $this->parseDeprecation($node, $path)) {
$alias->setDeprecated($deprecationInfo['package'], $deprecationInfo['version'], $deprecationInfo['message']);
}

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 Expand Up @@ -419,4 +429,41 @@ private function isElementValueNull(\DOMElement $element): bool

return 'true' === $element->getAttributeNS($namespaceUri, 'nil') || '1' === $element->getAttributeNS($namespaceUri, 'nil');
}

/**
* Parses the deprecation elements.
*
* @throws \InvalidArgumentException When the XML is invalid
*/
private function parseDeprecation(\DOMElement $node, string $path): array
{
$deprecatedNode = null;
foreach ($node->childNodes as $child) {
if (!$child instanceof \DOMElement || self::NAMESPACE_URI !== $child->namespaceURI) {
continue;
}
if ('deprecated' !== $child->localName) {
throw new \InvalidArgumentException(sprintf('Invalid child element "%s" defined for alias "%s" in "%s".', $child->localName, $node->getAttribute('id'), $path));
}

$deprecatedNode = $child;
}

if (null === $deprecatedNode) {
return [];
}

if (!$deprecatedNode->hasAttribute('package')) {
throw new \InvalidArgumentException(sprintf('The <deprecated> element in file "%s" must have a "package" attribute.', $path));
}
if (!$deprecatedNode->hasAttribute('version')) {
throw new \InvalidArgumentException(sprintf('The <deprecated> element in file "%s" must have a "version" attribute.', $path));
}

return [
'package' => $deprecatedNode->getAttribute('package'),
'version' => $deprecatedNode->getAttribute('version'),
'message' => trim($deprecatedNode->nodeValue),
];
}
}
Loading