Skip to content

[Routing] Allow aliases in #[Route] attribute #58819

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
Jan 25, 2025
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
46 changes: 46 additions & 0 deletions src/Symfony/Component/Routing/Attribute/DeprecatedAlias.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?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\Attribute;

/**
* This class is meant to be used in {@see Route} to define an alias for a route.
*/
class DeprecatedAlias
{
public function __construct(
private string $aliasName,
private string $package,
private string $version,
private string $message = '',
) {
}

public function getMessage(): string
{
return $this->message;
}

public function getAliasName(): string
{
return $this->aliasName;
}

public function getPackage(): string
{
return $this->package;
}

public function getVersion(): string
{
return $this->version;
}
}
53 changes: 38 additions & 15 deletions src/Symfony/Component/Routing/Attribute/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,28 @@ class Route
private array $localizedPaths = [];
private array $methods;
private array $schemes;
/**
* @var (string|DeprecatedAlias)[]
*/
private array $aliases = [];

/**
* @param string|array<string,string>|null $path The route path (i.e. "/user/login")
* @param string|null $name The route name (i.e. "app_user_login")
* @param array<string|\Stringable> $requirements Requirements for the route attributes, @see https://symfony.com/doc/current/routing.html#parameters-validation
* @param array<string, mixed> $options Options for the route (i.e. ['prefix' => '/api'])
* @param array<string, mixed> $defaults Default values for the route attributes and query parameters
* @param string|null $host The host for which this route should be active (i.e. "localhost")
* @param string|string[] $methods The list of HTTP methods allowed by this route
* @param string|string[] $schemes The list of schemes allowed by this route (i.e. "https")
* @param string|null $condition An expression that must evaluate to true for the route to be matched, @see https://symfony.com/doc/current/routing.html#matching-expressions
* @param int|null $priority The priority of the route if multiple ones are defined for the same path
* @param string|null $locale The locale accepted by the route
* @param string|null $format The format returned by the route (i.e. "json", "xml")
* @param bool|null $utf8 Whether the route accepts UTF-8 in its parameters
* @param bool|null $stateless Whether the route is defined as stateless or stateful, @see https://symfony.com/doc/current/routing.html#stateless-routes
* @param string|null $env The env in which the route is defined (i.e. "dev", "test", "prod")
* @param string|array<string,string>|null $path The route path (i.e. "/user/login")
* @param string|null $name The route name (i.e. "app_user_login")
* @param array<string|\Stringable> $requirements Requirements for the route attributes, @see https://symfony.com/doc/current/routing.html#parameters-validation
* @param array<string, mixed> $options Options for the route (i.e. ['prefix' => '/api'])
* @param array<string, mixed> $defaults Default values for the route attributes and query parameters
* @param string|null $host The host for which this route should be active (i.e. "localhost")
* @param string|string[] $methods The list of HTTP methods allowed by this route
* @param string|string[] $schemes The list of schemes allowed by this route (i.e. "https")
* @param string|null $condition An expression that must evaluate to true for the route to be matched, @see https://symfony.com/doc/current/routing.html#matching-expressions
* @param int|null $priority The priority of the route if multiple ones are defined for the same path
* @param string|null $locale The locale accepted by the route
* @param string|null $format The format returned by the route (i.e. "json", "xml")
* @param bool|null $utf8 Whether the route accepts UTF-8 in its parameters
* @param bool|null $stateless Whether the route is defined as stateless or stateful, @see https://symfony.com/doc/current/routing.html#stateless-routes
* @param string|null $env The env in which the route is defined (i.e. "dev", "test", "prod")
* @param string|DeprecatedAlias|(string|DeprecatedAlias)[] $alias The list of aliases for this route
*/
public function __construct(
string|array|null $path = null,
Expand All @@ -56,6 +61,7 @@ public function __construct(
?bool $utf8 = null,
?bool $stateless = null,
private ?string $env = null,
string|DeprecatedAlias|array $alias = [],
) {
if (\is_array($path)) {
$this->localizedPaths = $path;
Expand All @@ -64,6 +70,7 @@ public function __construct(
}
$this->setMethods($methods);
$this->setSchemes($schemes);
$this->setAliases($alias);

if (null !== $locale) {
$this->defaults['_locale'] = $locale;
Expand Down Expand Up @@ -201,6 +208,22 @@ public function getEnv(): ?string
{
return $this->env;
}

/**
* @return (string|DeprecatedAlias)[]
*/
public function getAliases(): array
{
return $this->aliases;
}

/**
* @param string|DeprecatedAlias|(string|DeprecatedAlias)[] $aliases
*/
public function setAliases(string|DeprecatedAlias|array $aliases): void
{
$this->aliases = \is_array($aliases) ? $aliases : [$aliases];
}
}

if (!class_exists(\Symfony\Component\Routing\Annotation\Route::class, false)) {
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Routing/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

7.3
---

* Allow aliases and deprecations in `#[Route]` attribute

7.2
---

Expand Down
24 changes: 24 additions & 0 deletions src/Symfony/Component/Routing/Loader/AttributeClassLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Loader\LoaderResolverInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Routing\Attribute\DeprecatedAlias;
use Symfony\Component\Routing\Attribute\Route as RouteAttribute;
use Symfony\Component\Routing\Exception\InvalidArgumentException;
use Symfony\Component\Routing\Exception\LogicException;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
Expand Down Expand Up @@ -107,6 +109,15 @@ public function load(mixed $class, ?string $type = null): RouteCollection
return $collection;
}
$fqcnAlias = false;

if (!$class->hasMethod('__invoke')) {
foreach ($this->getAttributes($class) as $attr) {
if ($attr->getAliases()) {
throw new InvalidArgumentException(\sprintf('Route aliases cannot be used on non-invokable class "%s".', $class->getName()));
}
}
}

foreach ($class->getMethods() as $method) {
$this->defaultRouteIndex = 0;
$routeNamesBefore = array_keys($collection->all());
Expand Down Expand Up @@ -230,6 +241,19 @@ protected function addRoute(RouteCollection $collection, object $attr, array $gl
} else {
$collection->add($name, $route, $priority);
}
foreach ($attr->getAliases() as $aliasAttribute) {
if ($aliasAttribute instanceof DeprecatedAlias) {
$alias = $collection->addAlias($aliasAttribute->getAliasName(), $name);
$alias->setDeprecated(
$aliasAttribute->getPackage(),
$aliasAttribute->getVersion(),
$aliasAttribute->getMessage()
);
continue;
}

$collection->addAlias($aliasAttribute, $name);
}
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/Symfony/Component/Routing/Tests/Attribute/RouteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/

namespace Symfony\Component\Routing\Tests\Annotation;
namespace Symfony\Component\Routing\Tests\Attribute;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Routing\Attribute\Route;
Expand Down Expand Up @@ -40,6 +40,7 @@ public static function getValidParameters(): iterable
['methods', 'getMethods', ['GET', 'POST']],
['host', 'getHost', '{locale}.example.com'],
['condition', 'getCondition', 'context.getMethod() == \'GET\''],
['alias', 'getAliases', ['alias', 'completely_different_name']],
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?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\Tests\Fixtures\AttributeFixtures;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/hello', alias: ['alias', 'completely_different_name'])]
class AliasClassController
{
#[Route('/world')]
public function actionWorld()
{
}

#[Route('/symfony')]
public function actionSymfony()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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\Tests\Fixtures\AttributeFixtures;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/path', name:'invokable_path', alias: ['alias', 'completely_different_name'])]
class AliasInvokableController
{
public function __invoke()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?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\Tests\Fixtures\AttributeFixtures;

use Symfony\Component\Routing\Attribute\Route;

class AliasRouteController
{
#[Route('/path', name: 'action_with_alias', alias: ['alias', 'completely_different_name'])]
public function action()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?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\Tests\Fixtures\AttributeFixtures;

use Symfony\Component\Routing\Attribute\DeprecatedAlias;
use Symfony\Component\Routing\Attribute\Route;

class DeprecatedAliasCustomMessageRouteController
{

#[Route('/path', name: 'action_with_deprecated_alias', alias: new DeprecatedAlias('my_other_alias_deprecated', 'MyBundleFixture', '1.0', message: '%alias_id% alias is deprecated.'))]
public function action()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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\Tests\Fixtures\AttributeFixtures;

use Symfony\Component\Routing\Attribute\DeprecatedAlias;
use Symfony\Component\Routing\Attribute\Route;

class DeprecatedAliasRouteController
{
#[Route('/path', name: 'action_with_deprecated_alias', alias: new DeprecatedAlias('my_other_alias_deprecated', 'MyBundleFixture', '1.0'))]
public function action()
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,9 @@ public function host()
public function condition()
{
}

#[Route(alias: ['alias', 'completely_different_name'])]
public function alias()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?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\Tests\Fixtures\AttributeFixtures;

use Symfony\Component\Routing\Attribute\DeprecatedAlias;
use Symfony\Component\Routing\Attribute\Route;

class MultipleDeprecatedAliasRouteController
{
#[Route('/path', name: 'action_with_multiple_deprecated_alias', alias: [
new DeprecatedAlias('my_first_alias_deprecated', 'MyFirstBundleFixture', '1.0'),
new DeprecatedAlias('my_second_alias_deprecated', 'MySecondBundleFixture', '2.0'),
new DeprecatedAlias('my_third_alias_deprecated', 'SurprisedThirdBundleFixture', '3.0'),
])]
public function action()
{
}
}
Loading
Loading