Нет описания

ControllerResolver.php 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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: '.$this->getControllerError($controller), $request->getPathInfo()));
  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: '.$this->getControllerError($callable), $request->getPathInfo()));
  77. }
  78. return $callable;
  79. }
  80. /**
  81. * Returns a callable for the given controller.
  82. *
  83. * @param string $controller A Controller string
  84. *
  85. * @return callable A PHP callable
  86. *
  87. * @throws \InvalidArgumentException When the controller cannot be created
  88. */
  89. protected function createController($controller)
  90. {
  91. if (!str_contains($controller, '::')) {
  92. $controller = $this->instantiateController($controller);
  93. if (!\is_callable($controller)) {
  94. throw new \InvalidArgumentException($this->getControllerError($controller));
  95. }
  96. return $controller;
  97. }
  98. [$class, $method] = explode('::', $controller, 2);
  99. try {
  100. $controller = [$this->instantiateController($class), $method];
  101. } catch (\Error|\LogicException $e) {
  102. try {
  103. if ((new \ReflectionMethod($class, $method))->isStatic()) {
  104. return $class.'::'.$method;
  105. }
  106. } catch (\ReflectionException $reflectionException) {
  107. throw $e;
  108. }
  109. throw $e;
  110. }
  111. if (!\is_callable($controller)) {
  112. throw new \InvalidArgumentException($this->getControllerError($controller));
  113. }
  114. return $controller;
  115. }
  116. /**
  117. * Returns an instantiated controller.
  118. *
  119. * @param string $class A class name
  120. *
  121. * @return object
  122. */
  123. protected function instantiateController($class)
  124. {
  125. return new $class();
  126. }
  127. private function getControllerError($callable): string
  128. {
  129. if (\is_string($callable)) {
  130. if (str_contains($callable, '::')) {
  131. $callable = explode('::', $callable, 2);
  132. } else {
  133. return sprintf('Function "%s" does not exist.', $callable);
  134. }
  135. }
  136. if (\is_object($callable)) {
  137. $availableMethods = $this->getClassMethodsWithoutMagicMethods($callable);
  138. $alternativeMsg = $availableMethods ? sprintf(' or use one of the available methods: "%s"', implode('", "', $availableMethods)) : '';
  139. return sprintf('Controller class "%s" cannot be called without a method name. You need to implement "__invoke"%s.', \get_class($callable), $alternativeMsg);
  140. }
  141. if (!\is_array($callable)) {
  142. return sprintf('Invalid type for controller given, expected string, array or object, got "%s".', \gettype($callable));
  143. }
  144. if (!isset($callable[0]) || !isset($callable[1]) || 2 !== \count($callable)) {
  145. return 'Invalid array callable, expected [controller, method].';
  146. }
  147. [$controller, $method] = $callable;
  148. if (\is_string($controller) && !class_exists($controller)) {
  149. return sprintf('Class "%s" does not exist.', $controller);
  150. }
  151. $className = \is_object($controller) ? \get_class($controller) : $controller;
  152. if (method_exists($controller, $method)) {
  153. return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
  154. }
  155. $collection = $this->getClassMethodsWithoutMagicMethods($controller);
  156. $alternatives = [];
  157. foreach ($collection as $item) {
  158. $lev = levenshtein($method, $item);
  159. if ($lev <= \strlen($method) / 3 || str_contains($item, $method)) {
  160. $alternatives[] = $item;
  161. }
  162. }
  163. asort($alternatives);
  164. $message = sprintf('Expected method "%s" on class "%s"', $method, $className);
  165. if (\count($alternatives) > 0) {
  166. $message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives));
  167. } else {
  168. $message .= sprintf('. Available methods: "%s".', implode('", "', $collection));
  169. }
  170. return $message;
  171. }
  172. private function getClassMethodsWithoutMagicMethods($classOrObject): array
  173. {
  174. $methods = get_class_methods($classOrObject);
  175. return array_filter($methods, function (string $method) {
  176. return 0 !== strncmp($method, '__', 2);
  177. });
  178. }
  179. }