Skip to content

[RFC][Routing] Added the Route attribute #37474

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
Sep 7, 2020
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
1 change: 1 addition & 0 deletions .github/patch-types.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
case false !== strpos($file, '/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Dummy.php'):
case false !== strpos($file, '/src/Symfony/Component/PropertyInfo/Tests/Fixtures/ParentDummy.php'):
case false !== strpos($file, '/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Php80Dummy.php'):
case false !== strpos($file, '/src/Symfony/Component/Routing/Tests/Fixtures/AttributeFixtures'):
case false !== strpos($file, '/src/Symfony/Component/Serializer/Tests/Normalizer/Features/ObjectOuter.php'):
case false !== strpos($file, '/src/Symfony/Component/VarDumper/Tests/Fixtures/NotLoadableClass.php'):
case false !== strpos($file, '/src/Symfony/Component/VarDumper/Tests/Fixtures/Php74.php') && \PHP_VERSION_ID < 70400:
Expand Down
57 changes: 54 additions & 3 deletions src/Symfony/Component/Routing/Annotation/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,18 @@

namespace Symfony\Component\Routing\Annotation;

use Attribute;

/**
* Annotation class for @Route().
*
* @Annotation
* @Target({"CLASS", "METHOD"})
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander M. Turek <me@derrabus.de>
*/
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
class Route
{
private $path;
Expand All @@ -34,12 +38,59 @@ class Route
private $priority;

/**
* @param array $data An array of key/value parameters
* @param array|string $data data array managed by the Doctrine Annotations library or the path
* @param array|string|null $path
* @param string[] $requirements
* @param string[] $methods
* @param string[] $schemes
*
* @throws \BadMethodCallException
*/
public function __construct(array $data)
{
public function __construct(
$data = [],
$path = null,
string $name = null,
array $requirements = [],
array $options = [],
array $defaults = [],
string $host = null,
array $methods = [],
array $schemes = [],
string $condition = null,
int $priority = null,
string $locale = null,
string $format = null,
bool $utf8 = null,
bool $stateless = null
) {
if (\is_string($data)) {
$data = ['path' => $data];
} elseif (!\is_array($data)) {
throw new \TypeError(sprintf('"%s": Argument $data is expected to be a string or array, got "%s".', __METHOD__, get_debug_type($data)));
}
if (null !== $path && !\is_string($path) && !\is_array($path)) {
throw new \TypeError(sprintf('"%s": Argument $path is expected to be a string, array or null, got "%s".', __METHOD__, get_debug_type($path)));
}

$data['path'] = $data['path'] ?? $path;
$data['name'] = $data['name'] ?? $name;
$data['requirements'] = $data['requirements'] ?? $requirements;
$data['options'] = $data['options'] ?? $options;
$data['defaults'] = $data['defaults'] ?? $defaults;
$data['host'] = $data['host'] ?? $host;
$data['methods'] = $data['methods'] ?? $methods;
$data['schemes'] = $data['schemes'] ?? $schemes;
$data['condition'] = $data['condition'] ?? $condition;
$data['priority'] = $data['priority'] ?? $priority;
$data['locale'] = $data['locale'] ?? $locale;
$data['format'] = $data['format'] ?? $format;
$data['utf8'] = $data['utf8'] ?? $utf8;
$data['stateless'] = $data['stateless'] ?? $stateless;

$data = array_filter($data, static function ($value): bool {
return null !== $value;
});

if (isset($data['localized_paths'])) {
throw new \BadMethodCallException(sprintf('Unknown property "localized_paths" on annotation "%s".', static::class));
}
Expand Down
74 changes: 61 additions & 13 deletions src/Symfony/Component/Routing/Loader/AnnotationClassLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,24 @@
* {
* }
* }
*
* On PHP 8, the annotation class can be used as an attribute as well:
* #[Route('/Blog')]
* class Blog
* {
* #[Route('/', name: 'blog_index')]
* public function index()
* {
* }
* #[Route('/{id}', name: 'blog_post', requirements: ["id" => '\d+'])]
* public function show()
* {
* }
* }

*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander M. Turek <me@derrabus.de>
*/
abstract class AnnotationClassLoader implements LoaderInterface
{
Expand All @@ -61,14 +77,14 @@ abstract class AnnotationClassLoader implements LoaderInterface
/**
* @var string
*/
protected $routeAnnotationClass = 'Symfony\\Component\\Routing\\Annotation\\Route';
protected $routeAnnotationClass = RouteAnnotation::class;

/**
* @var int
*/
protected $defaultRouteIndex = 0;

public function __construct(Reader $reader)
public function __construct(Reader $reader = null)
{
$this->reader = $reader;
}
Expand Down Expand Up @@ -108,19 +124,15 @@ public function load($class, string $type = null)

foreach ($class->getMethods() as $method) {
$this->defaultRouteIndex = 0;
foreach ($this->reader->getMethodAnnotations($method) as $annot) {
if ($annot instanceof $this->routeAnnotationClass) {
$this->addRoute($collection, $annot, $globals, $class, $method);
}
foreach ($this->getAnnotations($method) as $annot) {
$this->addRoute($collection, $annot, $globals, $class, $method);
}
}

if (0 === $collection->count() && $class->hasMethod('__invoke')) {
$globals = $this->resetGlobals();
foreach ($this->reader->getClassAnnotations($class) as $annot) {
if ($annot instanceof $this->routeAnnotationClass) {
$this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke'));
}
foreach ($this->getAnnotations($class) as $annot) {
$this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke'));
}
}

Expand All @@ -130,7 +142,7 @@ public function load($class, string $type = null)
/**
* @param RouteAnnotation $annot or an object that exposes a similar interface
*/
protected function addRoute(RouteCollection $collection, $annot, array $globals, \ReflectionClass $class, \ReflectionMethod $method)
protected function addRoute(RouteCollection $collection, object $annot, array $globals, \ReflectionClass $class, \ReflectionMethod $method)
{
$name = $annot->getName();
if (null === $name) {
Expand Down Expand Up @@ -257,7 +269,15 @@ protected function getGlobals(\ReflectionClass $class)
{
$globals = $this->resetGlobals();

if ($annot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass)) {
$annot = null;
if (\PHP_VERSION_ID >= 80000 && ($attribute = $class->getAttributes($this->routeAnnotationClass)[0] ?? null)) {
$annot = $attribute->newInstance();
}
if (!$annot && $this->reader) {
$annot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass);
}

if ($annot) {
if (null !== $annot->getName()) {
$globals['name'] = $annot->getName();
}
Expand Down Expand Up @@ -330,5 +350,33 @@ protected function createRoute(string $path, array $defaults, array $requirement
return new Route($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
}

abstract protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot);
abstract protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, object $annot);

/**
* @param \ReflectionClass|\ReflectionMethod $reflection
*
* @return iterable|RouteAnnotation[]
*/
private function getAnnotations(object $reflection): iterable
{
if (\PHP_VERSION_ID >= 80000) {
foreach ($reflection->getAttributes($this->routeAnnotationClass) as $attribute) {
yield $attribute->newInstance();
}
}

if (!$this->reader) {
return;
}

$anntotations = $reflection instanceof \ReflectionClass
? $this->reader->getClassAnnotations($reflection)
: $this->reader->getMethodAnnotations($reflection);

foreach ($anntotations as $annotation) {
if ($annotation instanceof $this->routeAnnotationClass) {
yield $annotation;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?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\AnnotationFixtures;

use Symfony\Component\Routing\Annotation\Route;

/**
* @Route("/1", name="route1", schemes={"https"}, methods={"GET"})
* @Route("/2", name="route2", schemes={"https"}, methods={"GET"})
*/
class BazClass
{
public function __invoke()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Symfony\Component\Routing\Tests\Fixtures\AnnotationFixtures;

use Symfony\Component\Routing\Annotation\Route;

class EncodingClass
{
/**
* @Route
*/
public function routeÀction()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Symfony\Component\Routing\Tests\Fixtures\AttributeFixtures;

use Symfony\Component\Routing\Annotation\Route;

class ActionPathController
{
#[Route('/path', name: 'action')]
public function action()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?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\Annotation\Route;

#[
Route(path: '/1', name: 'route1', schemes: ['https'], methods: ['GET']),
Route(path: '/2', name: 'route2', schemes: ['https'], methods: ['GET']),
]
class BazClass
{
public function __invoke()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Symfony\Component\Routing\Tests\Fixtures\AttributeFixtures;

use Symfony\Component\Routing\Annotation\Route;

class DefaultValueController
{
#[Route(path: '/{default}/path', name: 'action')]
public function action($default = 'value')
{
}

#[
Route(path: '/hello/{name<\w+>}', name: 'hello_without_default'),
Route(path: 'hello/{name<\w+>?Symfony}', name: 'hello_with_default'),
]
public function hello(string $name = 'World')
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Symfony\Component\Routing\Tests\Fixtures\AttributeFixtures;

use Symfony\Component\Routing\Annotation\Route;

class EncodingClass
{
#[Route]
public function routeÀction()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Symfony\Component\Routing\Tests\Fixtures\AttributeFixtures;

use Symfony\Component\Routing\Annotation\Route;

class ExplicitLocalizedActionPathController
{
#[Route(path: ['en' => '/path', 'nl' => '/pad'], name: 'action')]
public function action()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?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\Annotation\Route;

#[Route(path: '/defaults', locale: 'g_locale', format: 'g_format')]
class GlobalDefaultsClass
{
#[Route(path: '/specific-locale', name: 'specific_locale', locale: 's_locale')]
public function locale()
{
}

#[Route(path: '/specific-format', name: 'specific_format', format: 's_format')]
public function format()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Symfony\Component\Routing\Tests\Fixtures\AttributeFixtures;

use Symfony\Component\Routing\Annotation\Route;

#[Route(path: '/here', name: 'lol', methods: ["GET", "POST"], schemes: ['https'])]
class InvokableController
{
public function __invoke()
{
}
}
Loading