ControllerResolver.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 ?LoggerInterface $logger;
  25. private array $allowedControllerTypes = [];
  26. private array $allowedControllerAttributes = [AsController::class => AsController::class];
  27. public function __construct(?LoggerInterface $logger = null)
  28. {
  29. $this->logger = $logger;
  30. }
  31. /**
  32. * @param array<class-string> $types
  33. * @param array<class-string> $attributes
  34. */
  35. public function allowControllers(array $types = [], array $attributes = []): void
  36. {
  37. foreach ($types as $type) {
  38. $this->allowedControllerTypes[$type] = $type;
  39. }
  40. foreach ($attributes as $attribute) {
  41. $this->allowedControllerAttributes[$attribute] = $attribute;
  42. }
  43. }
  44. /**
  45. * @throws BadRequestException when the request has attribute "_check_controller_is_allowed" set to true and the controller is not allowed
  46. */
  47. public function getController(Request $request): callable|false
  48. {
  49. if (!$controller = $request->attributes->get('_controller')) {
  50. $this->logger?->warning('Unable to look for the controller as the "_controller" parameter is missing.');
  51. return false;
  52. }
  53. if (\is_array($controller)) {
  54. if (isset($controller[0]) && \is_string($controller[0]) && isset($controller[1])) {
  55. try {
  56. $controller[0] = $this->instantiateController($controller[0]);
  57. } catch (\Error|\LogicException $e) {
  58. if (\is_callable($controller)) {
  59. return $this->checkController($request, $controller);
  60. }
  61. throw $e;
  62. }
  63. }
  64. if (!\is_callable($controller)) {
  65. throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
  66. }
  67. return $this->checkController($request, $controller);
  68. }
  69. if (\is_object($controller)) {
  70. if (!\is_callable($controller)) {
  71. throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
  72. }
  73. return $this->checkController($request, $controller);
  74. }
  75. if (\function_exists($controller)) {
  76. return $this->checkController($request, $controller);
  77. }
  78. try {
  79. $callable = $this->createController($controller);
  80. } catch (\InvalidArgumentException $e) {
  81. throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$e->getMessage(), 0, $e);
  82. }
  83. if (!\is_callable($callable)) {
  84. throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($callable));
  85. }
  86. return $this->checkController($request, $callable);
  87. }
  88. /**
  89. * Returns a callable for the given controller.
  90. *
  91. * @throws \InvalidArgumentException When the controller cannot be created
  92. */
  93. protected function createController(string $controller): callable
  94. {
  95. if (!str_contains($controller, '::')) {
  96. $controller = $this->instantiateController($controller);
  97. if (!\is_callable($controller)) {
  98. throw new \InvalidArgumentException($this->getControllerError($controller));
  99. }
  100. return $controller;
  101. }
  102. [$class, $method] = explode('::', $controller, 2);
  103. try {
  104. $controller = [$this->instantiateController($class), $method];
  105. } catch (\Error|\LogicException $e) {
  106. try {
  107. if ((new \ReflectionMethod($class, $method))->isStatic()) {
  108. return $class.'::'.$method;
  109. }
  110. } catch (\ReflectionException) {
  111. throw $e;
  112. }
  113. throw $e;
  114. }
  115. if (!\is_callable($controller)) {
  116. throw new \InvalidArgumentException($this->getControllerError($controller));
  117. }
  118. return $controller;
  119. }
  120. /**
  121. * Returns an instantiated controller.
  122. */
  123. protected function instantiateController(string $class): object
  124. {
  125. return new $class();
  126. }
  127. private function getControllerError(mixed $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_debug_type($callable), $alternativeMsg);
  140. }
  141. if (!\is_array($callable)) {
  142. return \sprintf('Invalid type for controller given, expected string, array or object, got "%s".', get_debug_type($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_debug_type($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, fn (string $method) => 0 !== strncmp($method, '__', 2));
  176. }
  177. private function checkController(Request $request, callable $controller): callable
  178. {
  179. if (!$request->attributes->get('_check_controller_is_allowed', false)) {
  180. return $controller;
  181. }
  182. $r = null;
  183. if (\is_array($controller)) {
  184. [$class, $name] = $controller;
  185. $name = (\is_string($class) ? $class : $class::class).'::'.$name;
  186. } elseif (\is_object($controller) && !$controller instanceof \Closure) {
  187. $class = $controller;
  188. $name = $class::class.'::__invoke';
  189. } else {
  190. $r = new \ReflectionFunction($controller);
  191. $name = $r->name;
  192. if (str_contains($name, '{closure')) {
  193. $name = $class = \Closure::class;
  194. } elseif ($class = \PHP_VERSION_ID >= 80111 ? $r->getClosureCalledClass() : $r->getClosureScopeClass()) {
  195. $class = $class->name;
  196. $name = $class.'::'.$name;
  197. }
  198. }
  199. if ($class) {
  200. foreach ($this->allowedControllerTypes as $type) {
  201. if (is_a($class, $type, true)) {
  202. return $controller;
  203. }
  204. }
  205. }
  206. $r ??= new \ReflectionClass($class);
  207. foreach ($r->getAttributes() as $attribute) {
  208. if (isset($this->allowedControllerAttributes[$attribute->getName()])) {
  209. return $controller;
  210. }
  211. }
  212. if (str_contains($name, '@anonymous')) {
  213. $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);
  214. }
  215. if (-1 === $request->attributes->get('_check_controller_is_allowed')) {
  216. trigger_deprecation('symfony/http-kernel', '6.4', '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);
  217. return $controller;
  218. }
  219. 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));
  220. }
  221. }