vendor/symfony/http-kernel/Controller/ControllerResolver.php line 86

Open in your IDE?
  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)
  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. try {
  44. // We cannot just check is_callable but have to use reflection because a non-static method
  45. // can still be called statically in PHP but we don't want that. This is deprecated in PHP 7, so we
  46. // could simplify this with PHP 8.
  47. if ((new \ReflectionMethod($controller[0], $controller[1]))->isStatic()) {
  48. return $controller;
  49. }
  50. } catch (\ReflectionException $reflectionException) {
  51. throw $e;
  52. }
  53. throw $e;
  54. }
  55. }
  56. if (!\is_callable($controller)) {
  57. throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
  58. }
  59. return $controller;
  60. }
  61. if (\is_object($controller)) {
  62. if (!\is_callable($controller)) {
  63. throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
  64. }
  65. return $controller;
  66. }
  67. if (\function_exists($controller)) {
  68. return $controller;
  69. }
  70. try {
  71. $callable = $this->createController($controller);
  72. } catch (\InvalidArgumentException $e) {
  73. throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$e->getMessage(), 0, $e);
  74. }
  75. if (!\is_callable($callable)) {
  76. throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($callable));
  77. }
  78. return $callable;
  79. }
  80. /**
  81. * Returns a callable for the given controller.
  82. *
  83. * @return callable
  84. *
  85. * @throws \InvalidArgumentException When the controller cannot be created
  86. */
  87. protected function createController(string $controller)
  88. {
  89. if (!str_contains($controller, '::')) {
  90. $controller = $this->instantiateController($controller);
  91. if (!\is_callable($controller)) {
  92. throw new \InvalidArgumentException($this->getControllerError($controller));
  93. }
  94. return $controller;
  95. }
  96. [$class, $method] = explode('::', $controller, 2);
  97. try {
  98. $controller = [$this->instantiateController($class), $method];
  99. } catch (\Error|\LogicException $e) {
  100. try {
  101. if ((new \ReflectionMethod($class, $method))->isStatic()) {
  102. return $class.'::'.$method;
  103. }
  104. } catch (\ReflectionException $reflectionException) {
  105. throw $e;
  106. }
  107. throw $e;
  108. }
  109. if (!\is_callable($controller)) {
  110. throw new \InvalidArgumentException($this->getControllerError($controller));
  111. }
  112. return $controller;
  113. }
  114. /**
  115. * Returns an instantiated controller.
  116. *
  117. * @return object
  118. */
  119. protected function instantiateController(string $class)
  120. {
  121. return new $class();
  122. }
  123. private function getControllerError($callable): string
  124. {
  125. if (\is_string($callable)) {
  126. if (str_contains($callable, '::')) {
  127. $callable = explode('::', $callable, 2);
  128. } else {
  129. return sprintf('Function "%s" does not exist.', $callable);
  130. }
  131. }
  132. if (\is_object($callable)) {
  133. $availableMethods = $this->getClassMethodsWithoutMagicMethods($callable);
  134. $alternativeMsg = $availableMethods ? sprintf(' or use one of the available methods: "%s"', implode('", "', $availableMethods)) : '';
  135. return sprintf('Controller class "%s" cannot be called without a method name. You need to implement "__invoke"%s.', get_debug_type($callable), $alternativeMsg);
  136. }
  137. if (!\is_array($callable)) {
  138. return sprintf('Invalid type for controller given, expected string, array or object, got "%s".', get_debug_type($callable));
  139. }
  140. if (!isset($callable[0]) || !isset($callable[1]) || 2 !== \count($callable)) {
  141. return 'Invalid array callable, expected [controller, method].';
  142. }
  143. [$controller, $method] = $callable;
  144. if (\is_string($controller) && !class_exists($controller)) {
  145. return sprintf('Class "%s" does not exist.', $controller);
  146. }
  147. $className = \is_object($controller) ? get_debug_type($controller) : $controller;
  148. if (method_exists($controller, $method)) {
  149. return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
  150. }
  151. $collection = $this->getClassMethodsWithoutMagicMethods($controller);
  152. $alternatives = [];
  153. foreach ($collection as $item) {
  154. $lev = levenshtein($method, $item);
  155. if ($lev <= \strlen($method) / 3 || str_contains($item, $method)) {
  156. $alternatives[] = $item;
  157. }
  158. }
  159. asort($alternatives);
  160. $message = sprintf('Expected method "%s" on class "%s"', $method, $className);
  161. if (\count($alternatives) > 0) {
  162. $message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives));
  163. } else {
  164. $message .= sprintf('. Available methods: "%s".', implode('", "', $collection));
  165. }
  166. return $message;
  167. }
  168. private function getClassMethodsWithoutMagicMethods($classOrObject): array
  169. {
  170. $methods = get_class_methods($classOrObject);
  171. return array_filter($methods, function (string $method) {
  172. return 0 !== strncmp($method, '__', 2);
  173. });
  174. }
  175. }