ControllerResolver.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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\Log\LoggerInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. /**
  14. * This implementation uses the '_controller' request attribute to determine
  15. * the controller to execute.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. * @author Tobias Schultze <http://tobion.de>
  19. */
  20. class ControllerResolver implements ControllerResolverInterface
  21. {
  22. private $logger;
  23. public function __construct(LoggerInterface $logger = null)
  24. {
  25. $this->logger = $logger;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function getController(Request $request): callable|false
  31. {
  32. if (!$controller = $request->attributes->get('_controller')) {
  33. if (null !== $this->logger) {
  34. $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.');
  35. }
  36. return false;
  37. }
  38. if (\is_array($controller)) {
  39. if (isset($controller[0]) && \is_string($controller[0]) && isset($controller[1])) {
  40. try {
  41. $controller[0] = $this->instantiateController($controller[0]);
  42. } catch (\Error|\LogicException $e) {
  43. if (\is_callable($controller)) {
  44. return $controller;
  45. }
  46. throw $e;
  47. }
  48. }
  49. if (!\is_callable($controller)) {
  50. throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
  51. }
  52. return $controller;
  53. }
  54. if (\is_object($controller)) {
  55. if (!\is_callable($controller)) {
  56. throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
  57. }
  58. return $controller;
  59. }
  60. if (\function_exists($controller)) {
  61. return $controller;
  62. }
  63. try {
  64. $callable = $this->createController($controller);
  65. } catch (\InvalidArgumentException $e) {
  66. throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$e->getMessage(), 0, $e);
  67. }
  68. if (!\is_callable($callable)) {
  69. throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($callable));
  70. }
  71. return $callable;
  72. }
  73. /**
  74. * Returns a callable for the given controller.
  75. *
  76. * @throws \InvalidArgumentException When the controller cannot be created
  77. */
  78. protected function createController(string $controller): callable
  79. {
  80. if (!str_contains($controller, '::')) {
  81. $controller = $this->instantiateController($controller);
  82. if (!\is_callable($controller)) {
  83. throw new \InvalidArgumentException($this->getControllerError($controller));
  84. }
  85. return $controller;
  86. }
  87. [$class, $method] = explode('::', $controller, 2);
  88. try {
  89. $controller = [$this->instantiateController($class), $method];
  90. } catch (\Error|\LogicException $e) {
  91. try {
  92. if ((new \ReflectionMethod($class, $method))->isStatic()) {
  93. return $class.'::'.$method;
  94. }
  95. } catch (\ReflectionException $reflectionException) {
  96. throw $e;
  97. }
  98. throw $e;
  99. }
  100. if (!\is_callable($controller)) {
  101. throw new \InvalidArgumentException($this->getControllerError($controller));
  102. }
  103. return $controller;
  104. }
  105. /**
  106. * Returns an instantiated controller.
  107. */
  108. protected function instantiateController(string $class): object
  109. {
  110. return new $class();
  111. }
  112. private function getControllerError(mixed $callable): string
  113. {
  114. if (\is_string($callable)) {
  115. if (str_contains($callable, '::')) {
  116. $callable = explode('::', $callable, 2);
  117. } else {
  118. return sprintf('Function "%s" does not exist.', $callable);
  119. }
  120. }
  121. if (\is_object($callable)) {
  122. $availableMethods = $this->getClassMethodsWithoutMagicMethods($callable);
  123. $alternativeMsg = $availableMethods ? sprintf(' or use one of the available methods: "%s"', implode('", "', $availableMethods)) : '';
  124. return sprintf('Controller class "%s" cannot be called without a method name. You need to implement "__invoke"%s.', get_debug_type($callable), $alternativeMsg);
  125. }
  126. if (!\is_array($callable)) {
  127. return sprintf('Invalid type for controller given, expected string, array or object, got "%s".', get_debug_type($callable));
  128. }
  129. if (!isset($callable[0]) || !isset($callable[1]) || 2 !== \count($callable)) {
  130. return 'Invalid array callable, expected [controller, method].';
  131. }
  132. [$controller, $method] = $callable;
  133. if (\is_string($controller) && !class_exists($controller)) {
  134. return sprintf('Class "%s" does not exist.', $controller);
  135. }
  136. $className = \is_object($controller) ? get_debug_type($controller) : $controller;
  137. if (method_exists($controller, $method)) {
  138. return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
  139. }
  140. $collection = $this->getClassMethodsWithoutMagicMethods($controller);
  141. $alternatives = [];
  142. foreach ($collection as $item) {
  143. $lev = levenshtein($method, $item);
  144. if ($lev <= \strlen($method) / 3 || str_contains($item, $method)) {
  145. $alternatives[] = $item;
  146. }
  147. }
  148. asort($alternatives);
  149. $message = sprintf('Expected method "%s" on class "%s"', $method, $className);
  150. if (\count($alternatives) > 0) {
  151. $message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives));
  152. } else {
  153. $message .= sprintf('. Available methods: "%s".', implode('", "', $collection));
  154. }
  155. return $message;
  156. }
  157. private function getClassMethodsWithoutMagicMethods($classOrObject): array
  158. {
  159. $methods = get_class_methods($classOrObject);
  160. return array_filter($methods, function (string $method) {
  161. return 0 !== strncmp($method, '__', 2);
  162. });
  163. }
  164. }