ContainerControllerResolver.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 createController($controller)
  29. {
  30. if (1 === substr_count($controller, ':')) {
  31. $controller = str_replace(':', '::', $controller);
  32. // TODO deprecate this in 5.1
  33. }
  34. return parent::createController($controller);
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. protected function instantiateController($class)
  40. {
  41. if ($this->container->has($class)) {
  42. return $this->container->get($class);
  43. }
  44. try {
  45. return parent::instantiateController($class);
  46. } catch (\Error $e) {
  47. }
  48. $this->throwExceptionIfControllerWasRemoved($class, $e);
  49. if ($e instanceof \ArgumentCountError) {
  50. throw new \InvalidArgumentException(sprintf('Controller "%s" has required constructor arguments and does not exist in the container. Did you forget to define such a service?', $class), 0, $e);
  51. }
  52. throw new \InvalidArgumentException(sprintf('Controller "%s" does neither exist as service nor as class', $class), 0, $e);
  53. }
  54. private function throwExceptionIfControllerWasRemoved(string $controller, \Throwable $previous)
  55. {
  56. if ($this->container instanceof Container && isset($this->container->getRemovedIds()[$controller])) {
  57. 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);
  58. }
  59. }
  60. }