Açıklama Yok

ContainerControllerResolver.php 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. $class = ltrim($class, '\\');
  42. if ($this->container->has($class)) {
  43. return $this->container->get($class);
  44. }
  45. try {
  46. return parent::instantiateController($class);
  47. } catch (\Error $e) {
  48. }
  49. $this->throwExceptionIfControllerWasRemoved($class, $e);
  50. if ($e instanceof \ArgumentCountError) {
  51. 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);
  52. }
  53. throw new \InvalidArgumentException(sprintf('Controller "%s" does neither exist as service nor as class.', $class), 0, $e);
  54. }
  55. private function throwExceptionIfControllerWasRemoved(string $controller, \Throwable $previous)
  56. {
  57. if ($this->container instanceof Container && isset($this->container->getRemovedIds()[$controller])) {
  58. 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);
  59. }
  60. }
  61. }