ControllerResolver.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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\Bundle\FrameworkBundle\Controller;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\DependencyInjection\ContainerAwareInterface;
  13. use Symfony\Component\DependencyInjection\ContainerInterface;
  14. use Symfony\Component\HttpKernel\Controller\ControllerResolver as BaseControllerResolver;
  15. /**
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class ControllerResolver extends BaseControllerResolver
  19. {
  20. protected $container;
  21. protected $parser;
  22. public function __construct(ContainerInterface $container, ControllerNameParser $parser, LoggerInterface $logger = null)
  23. {
  24. $this->container = $container;
  25. $this->parser = $parser;
  26. parent::__construct($logger);
  27. }
  28. /**
  29. * Returns a callable for the given controller.
  30. *
  31. * @param string $controller A Controller string
  32. *
  33. * @return mixed A PHP callable
  34. *
  35. * @throws \LogicException When the name could not be parsed
  36. * @throws \InvalidArgumentException When the controller class does not exist
  37. */
  38. protected function createController($controller)
  39. {
  40. if (false === strpos($controller, '::')) {
  41. $count = substr_count($controller, ':');
  42. if (2 == $count) {
  43. // controller in the a:b:c notation then
  44. $controller = $this->parser->parse($controller);
  45. } elseif (1 == $count) {
  46. // controller in the service:method notation
  47. list($service, $method) = explode(':', $controller, 2);
  48. return array($this->container->get($service), $method);
  49. } elseif ($this->container->has($controller) && method_exists($service = $this->container->get($controller), '__invoke')) {
  50. return $service;
  51. } else {
  52. throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
  53. }
  54. }
  55. return parent::createController($controller);
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. protected function instantiateController($class)
  61. {
  62. if ($this->container->has($class)) {
  63. return $this->container->get($class);
  64. }
  65. $controller = parent::instantiateController($class);
  66. if ($controller instanceof ContainerAwareInterface) {
  67. $controller->setContainer($this->container);
  68. }
  69. return $controller;
  70. }
  71. }