ContainerControllerResolver.php 2.2 KB

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. /**
  14. * A controller resolver searching for a controller in a psr-11 container when using the "service:method" notation.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
  18. */
  19. class ContainerControllerResolver extends ControllerResolver
  20. {
  21. protected $container;
  22. public function __construct(ContainerInterface $container, LoggerInterface $logger = null)
  23. {
  24. $this->container = $container;
  25. parent::__construct($logger);
  26. }
  27. /**
  28. * Returns a callable for the given controller.
  29. *
  30. * @param string $controller A Controller string
  31. *
  32. * @return mixed A PHP callable
  33. *
  34. * @throws \LogicException When the name could not be parsed
  35. * @throws \InvalidArgumentException When the controller class does not exist
  36. */
  37. protected function createController($controller)
  38. {
  39. if (false !== strpos($controller, '::')) {
  40. return parent::createController($controller);
  41. }
  42. if (1 == substr_count($controller, ':')) {
  43. // controller in the "service:method" notation
  44. list($service, $method) = explode(':', $controller, 2);
  45. return array($this->container->get($service), $method);
  46. }
  47. if ($this->container->has($controller) && method_exists($service = $this->container->get($controller), '__invoke')) {
  48. // invokable controller in the "service" notation
  49. return $service;
  50. }
  51. throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. protected function instantiateController($class)
  57. {
  58. if ($this->container->has($class)) {
  59. return $this->container->get($class);
  60. }
  61. return parent::instantiateController($class);
  62. }
  63. }