ControllerResolver.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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\Exception\BadRequestException;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpKernel\Attribute\AsController;
  15. /**
  16. * This implementation uses the '_controller' request attribute to determine
  17. * the controller to execute.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. * @author Tobias Schultze <http://tobion.de>
  21. */
  22. class ControllerResolver implements ControllerResolverInterface
  23. {
  24. private array $allowedControllerTypes = [];
  25. private array $allowedControllerAttributes = [AsController::class => AsController::class];
  26. public function __construct(
  27. private ?LoggerInterface $logger = null,
  28. ) {
  29. }
  30. /**
  31. * @param array<class-string> $types
  32. * @param array<class-string> $attributes
  33. */
  34. public function allowControllers(array $types = [], array $attributes = []): void
  35. {
  36. foreach ($types as $type) {
  37. $this->allowedControllerTypes[$type] = $type;
  38. }
  39. foreach ($attributes as $attribute) {
  40. $this->allowedControllerAttributes[$attribute] = $attribute;
  41. }
  42. }
  43. /**
  44. * @throws BadRequestException when the request has attribute "_check_controller_is_allowed" set to true and the controller is not allowed
  45. */
  46. public function getController(Request $request): callable|false
  47. {
  48. if (!$controller = $request->attributes->get('_controller')) {
  49. $this->logger?->warning('Unable to look for the controller as the "_controller" parameter is missing.');
  50. return false;
  51. }
  52. if (\is_array($controller)) {
  53. if (isset($controller[0]) && \is_string($controller[0]) && isset($controller[1])) {
  54. try {
  55. $controller[0] = $this->instantiateController($controller[0]);
  56. } catch (\Error|\LogicException $e) {
  57. if (\is_callable($controller)) {
  58. return $this->checkController($request, $controller);
  59. }
  60. throw $e;
  61. }
  62. }
  63. if (!\is_callable($controller)) {
  64. throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
  65. }
  66. return $this->checkController($request, $controller);
  67. }
  68. if (\is_object($controller)) {
  69. if (!\is_callable($controller)) {
  70. throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
  71. }
  72. return $this->checkController($request, $controller);
  73. }
  74. if (\function_exists($controller)) {
  75. return $this->checkController($request, $controller);
  76. }
  77. try {
  78. $callable = $this->createController($controller);
  79. } catch (\InvalidArgumentException $e) {
  80. throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$e->getMessage(), 0, $e);
  81. }
  82. if (!\is_callable($callable)) {
  83. throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($callable));
  84. }
  85. return $this->checkController($request, $callable);
  86. }
  87. /**
  88. * Returns a callable for the given controller.
  89. *
  90. * @throws \InvalidArgumentException When the controller cannot be created
  91. */
  92. protected function createController(string $controller): callable
  93. {
  94. if (!str_contains($controller, '::')) {
  95. $controller = $this->instantiateController($controller);
  96. if (!\is_callable($controller)) {
  97. throw new \InvalidArgumentException($this->getControllerError($controller));
  98. }
  99. return $controller;
  100. }
  101. [$class, $method] = explode('::', $controller, 2);
  102. try {
  103. $controller = [$this->instantiateController($class), $method];
  104. } catch (\Error|\LogicException $e) {
  105. try {
  106. if ((new \ReflectionMethod($class, $method))->isStatic()) {
  107. return $class.'::'.$method;
  108. }
  109. } catch (\ReflectionException) {
  110. throw $e;
  111. }
  112. throw $e;
  113. }
  114. if (!\is_callable($controller)) {
  115. throw new \InvalidArgumentException($this->getControllerError($controller));
  116. }
  117. return $controller;
  118. }
  119. /**
  120. * Returns an instantiated controller.
  121. */
  122. protected function instantiateController(string $class): object
  123. {
  124. return new $class();
  125. }
  126. private function getControllerError(mixed $callable): string
  127. {
  128. if (\is_string($callable)) {
  129. if (str_contains($callable, '::')) {
  130. $callable = explode('::', $callable, 2);
  131. } else {
  132. return \sprintf('Function "%s" does not exist.', $callable);
  133. }
  134. }
  135. if (\is_object($callable)) {
  136. $availableMethods = $this->getClassMethodsWithoutMagicMethods($callable);
  137. $alternativeMsg = $availableMethods ? \sprintf(' or use one of the available methods: "%s"', implode('", "', $availableMethods)) : '';
  138. return \sprintf('Controller class "%s" cannot be called without a method name. You need to implement "__invoke"%s.', get_debug_type($callable), $alternativeMsg);
  139. }
  140. if (!\is_array($callable)) {
  141. return \sprintf('Invalid type for controller given, expected string, array or object, got "%s".', get_debug_type($callable));
  142. }
  143. if (!isset($callable[0]) || !isset($callable[1]) || 2 !== \count($callable)) {
  144. return 'Invalid array callable, expected [controller, method].';
  145. }
  146. [$controller, $method] = $callable;
  147. if (\is_string($controller) && !class_exists($controller)) {
  148. return \sprintf('Class "%s" does not exist.', $controller);
  149. }
  150. $className = \is_object($controller) ? get_debug_type($controller) : $controller;
  151. if (method_exists($controller, $method)) {
  152. return \sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
  153. }
  154. $collection = $this->getClassMethodsWithoutMagicMethods($controller);
  155. $alternatives = [];
  156. foreach ($collection as $item) {
  157. $lev = levenshtein($method, $item);
  158. if ($lev <= \strlen($method) / 3 || str_contains($item, $method)) {
  159. $alternatives[] = $item;
  160. }
  161. }
  162. asort($alternatives);
  163. $message = \sprintf('Expected method "%s" on class "%s"', $method, $className);
  164. if (\count($alternatives) > 0) {
  165. $message .= \sprintf(', did you mean "%s"?', implode('", "', $alternatives));
  166. } else {
  167. $message .= \sprintf('. Available methods: "%s".', implode('", "', $collection));
  168. }
  169. return $message;
  170. }
  171. private function getClassMethodsWithoutMagicMethods($classOrObject): array
  172. {
  173. $methods = get_class_methods($classOrObject);
  174. return array_filter($methods, fn (string $method) => 0 !== strncmp($method, '__', 2));
  175. }
  176. private function checkController(Request $request, callable $controller): callable
  177. {
  178. if (!$request->attributes->get('_check_controller_is_allowed', false)) {
  179. return $controller;
  180. }
  181. $r = null;
  182. if (\is_array($controller)) {
  183. [$class, $name] = $controller;
  184. $name = (\is_string($class) ? $class : $class::class).'::'.$name;
  185. } elseif (\is_object($controller) && !$controller instanceof \Closure) {
  186. $class = $controller;
  187. $name = $class::class.'::__invoke';
  188. } else {
  189. $r = new \ReflectionFunction($controller);
  190. $name = $r->name;
  191. if ($r->isAnonymous()) {
  192. $name = $class = \Closure::class;
  193. } elseif ($class = $r->getClosureCalledClass()) {
  194. $class = $class->name;
  195. $name = $class.'::'.$name;
  196. }
  197. }
  198. if ($class) {
  199. foreach ($this->allowedControllerTypes as $type) {
  200. if (is_a($class, $type, true)) {
  201. return $controller;
  202. }
  203. }
  204. }
  205. $r ??= new \ReflectionClass($class);
  206. foreach ($r->getAttributes() as $attribute) {
  207. if (isset($this->allowedControllerAttributes[$attribute->getName()])) {
  208. return $controller;
  209. }
  210. }
  211. if (str_contains($name, '@anonymous')) {
  212. $name = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)?[0-9a-fA-F]++/', fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $name);
  213. }
  214. throw new BadRequestException(\sprintf('Callable "%s()" is not allowed as a controller. Did you miss tagging it with "#[AsController]" or registering its type with "%s::allowControllers()"?', $name, self::class));
  215. }
  216. }