ControllerResolver.php 6.7KB

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