菜谱项目

ContainerControllerResolver.php 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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\HttpFoundation\Request;
  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. /**
  29. * {@inheritdoc}
  30. */
  31. public function getController(Request $request)
  32. {
  33. $controller = parent::getController($request);
  34. if (is_array($controller) && isset($controller[0]) && is_string($controller[0]) && $this->container->has($controller[0])) {
  35. $controller[0] = $this->instantiateController($controller[0]);
  36. }
  37. return $controller;
  38. }
  39. /**
  40. * Returns a callable for the given controller.
  41. *
  42. * @param string $controller A Controller string
  43. *
  44. * @return mixed A PHP callable
  45. *
  46. * @throws \LogicException When the name could not be parsed
  47. * @throws \InvalidArgumentException When the controller class does not exist
  48. */
  49. protected function createController($controller)
  50. {
  51. if (false !== strpos($controller, '::')) {
  52. return parent::createController($controller);
  53. }
  54. if (1 == substr_count($controller, ':')) {
  55. // controller in the "service:method" notation
  56. list($service, $method) = explode(':', $controller, 2);
  57. return array($this->container->get($service), $method);
  58. }
  59. if ($this->container->has($controller) && method_exists($service = $this->container->get($controller), '__invoke')) {
  60. // invokable controller in the "service" notation
  61. return $service;
  62. }
  63. throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. protected function instantiateController($class)
  69. {
  70. if ($this->container->has($class)) {
  71. return $this->container->get($class);
  72. }
  73. return parent::instantiateController($class);
  74. }
  75. }