Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[FrameworkBundle] Enable controller service with #[Route] attribute #60081

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
Mar 29, 2025

Conversation

GromNaN
Copy link
Member

@GromNaN GromNaN commented Mar 28, 2025

Q A
Branch? 7.3
Bug fix? no
New feature? yes
Deprecations? no
Issues -
License MIT

The #[AsController] attribute has 2 purposes:

In this PR, I propose to add the tag argument_resolver.service on services when the class has the #[Route] attribute. Removing the need for #[AsController] on classes that use the #[Route] attribute.
I assume that if there is a route, it is a controller.

Diff (from the docs):

  namespace App\Controller;

  use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\HttpKernel\Attribute\AsController;
  use Symfony\Component\Routing\Attribute\Route;

- #[AsController]
  class HelloController
  {
      #[Route('/hello', name: 'hello', methods: ['GET'])]
      public function index(): Response
      {
          // ...
      }
  }

Copy link
Member

@yceruto yceruto left a comment

Choose a reason for hiding this comment

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

Good idea!

Copy link
Member

@fabpot fabpot left a comment

Choose a reason for hiding this comment

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

Seems like a good idea to me.

Copy link
Member

@nicolas-grekas nicolas-grekas left a comment

Choose a reason for hiding this comment

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

Just saying: It might be interesting to check the perf overhead of scanning all methods instead of just all classes.
This attribute is not the only one that triggers this scan so my comment is not a blocker, but still something I have in mind when reviewing :)

src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md Outdated Show resolved Hide resolved
@antonkomarev
Copy link

@nicolas-grekas is there caching of attribute usage? Then it will only affect cache warm up.

@nicolas-grekas
Copy link
Member

Yes, I'm thinking about optimizing the compile time indeed. At runtime, it doesn't matter.

@fabpot
Copy link
Member

fabpot commented Mar 29, 2025

Thank you @GromNaN.

@fabpot fabpot merged commit 981b556 into symfony:7.3 Mar 29, 2025
5 of 8 checks passed
@GromNaN GromNaN deleted the ascontroller branch March 30, 2025 06:08
@nicolas-grekas
Copy link
Member

I just realized that this PR is missing some integration with https://github.com/symfony/symfony/pull/52471/files
Aka it won't play well with ESI fragments.

@GromNaN
Copy link
Member Author

GromNaN commented Apr 14, 2025

I wasn't sure for security reasons. Requiring the #[AsController] explicitly seems more safe.

@nicolas-grekas
Copy link
Member

Which security problem could this lead to? If a method is registered as a controller, it's safe to be used as a fragment to me.

@nicolas-grekas
Copy link
Member

nicolas-grekas commented Apr 14, 2025

Here is the patch that should do it.

I'm not submitting it as a PR because it might be not needed in the end: the error message is self explanatory and explains one should use #[AsController] for the fragment to be rendered.
This might not provide the best DX out of the box though.
For thoughts.

diff --git a/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php b/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php
index 12bcd4c2dd..b8e5623476 100644
--- a/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php
+++ b/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php
@@ -15,6 +15,7 @@ use Psr\Log\LoggerInterface;
 use Symfony\Component\HttpFoundation\Exception\BadRequestException;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpKernel\Attribute\AsController;
+use Symfony\Component\Routing\Attribute\Route;
 
 /**
  * This implementation uses the '_controller' request attribute to determine
@@ -26,7 +27,10 @@ use Symfony\Component\HttpKernel\Attribute\AsController;
 class ControllerResolver implements ControllerResolverInterface
 {
     private array $allowedControllerTypes = [];
-    private array $allowedControllerAttributes = [AsController::class => AsController::class];
+    private array $allowedControllerAttributes = [
+        AsController::class => AsController::class,
+        Route::class => Route::class,
+    ];
 
     public function __construct(
         private ?LoggerInterface $logger = null,
@@ -228,12 +232,14 @@ class ControllerResolver implements ControllerResolverInterface
         }
 
         $r = null;
+        $method = null;
 
         if (\is_array($controller)) {
-            [$class, $name] = $controller;
-            $name = (\is_string($class) ? $class : $class::class).'::'.$name;
+            [$class, $method] = $controller;
+            $name = (\is_string($class) ? $class : $class::class).'::'.$method;
         } elseif (\is_object($controller) && !$controller instanceof \Closure) {
             $class = $controller;
+            $method = '__invoke';
             $name = $class::class.'::__invoke';
         } else {
             $r = new \ReflectionFunction($controller);
@@ -255,14 +261,16 @@ class ControllerResolver implements ControllerResolverInterface
             }
         }
 
-        $r ??= new \ReflectionClass($class);
+        do {
+            $r ??= new \ReflectionClass($class);
 
-        foreach ($r->getAttributes() as $attribute) {
-            if (isset($this->allowedControllerAttributes[$attribute->getName()])) {
-                return $controller;
+            foreach ($r->getAttributes() as $attribute) {
+                if (isset($this->allowedControllerAttributes[$attribute->getName()])) {
+                    return $controller;
+                }
             }
-        }
-
+        } while ($method && $r instanceof \ReflectionClass && method_exists($class, $method) && $r = new \ReflectionMethod($class, $method));
+    
         if (str_contains($name, '@anonymous')) {
             $name = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)?[0-9a-fA-F]++/', fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $name);
         }

@fabpot fabpot mentioned this pull request May 2, 2025
@nicolas-grekas
Copy link
Member

NVM my latest comments, such controllers will be added to the set of allowed controllers thanks to the tag and to #53985

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.