ContainerControllerResolver.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\Controller;
  11. use Psr\Container\ContainerInterface;
  12. use Psr\Log\LoggerInterface;
  13. use Symfony\Component\DependencyInjection\Container;
  14. /**
  15. * A controller resolver searching for a controller in a psr-11 container when using the "service::method" notation.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
  19. */
  20. class ContainerControllerResolver extends ControllerResolver
  21. {
  22. protected $container;
  23. public function __construct(ContainerInterface $container, ?LoggerInterface $logger = null)
  24. {
  25. $this->container = $container;
  26. parent::__construct($logger);
  27. }
  28. protected function instantiateController(string $class): object
  29. {
  30. $class = ltrim($class, '\\');
  31. if ($this->container->has($class)) {
  32. return $this->container->get($class);
  33. }
  34. try {
  35. return parent::instantiateController($class);
  36. } catch (\Error $e) {
  37. }
  38. $this->throwExceptionIfControllerWasRemoved($class, $e);
  39. if ($e instanceof \ArgumentCountError) {
  40. throw new \InvalidArgumentException(\sprintf('Controller "%s" has required constructor arguments and does not exist in the container. Did you forget to define the controller as a service?', $class), 0, $e);
  41. }
  42. throw new \InvalidArgumentException(\sprintf('Controller "%s" does neither exist as service nor as class.', $class), 0, $e);
  43. }
  44. private function throwExceptionIfControllerWasRemoved(string $controller, \Throwable $previous): void
  45. {
  46. if ($this->container instanceof Container && isset($this->container->getRemovedIds()[$controller])) {
  47. throw new \InvalidArgumentException(\sprintf('Controller "%s" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?', $controller), 0, $previous);
  48. }
  49. }
  50. }