ControllerResolver.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. * ControllerResolver.
  15. *
  16. * This implementation uses the '_controller' request attribute to determine
  17. * the controller to execute and uses the request attributes to determine
  18. * the controller method arguments.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class ControllerResolver implements ArgumentResolverInterface, ControllerResolverInterface
  23. {
  24. private $logger;
  25. /**
  26. * If the ...$arg functionality is available.
  27. *
  28. * Requires at least PHP 5.6.0 or HHVM 3.9.1
  29. *
  30. * @var bool
  31. */
  32. private $supportsVariadic;
  33. /**
  34. * If scalar types exists.
  35. *
  36. * @var bool
  37. */
  38. private $supportsScalarTypes;
  39. /**
  40. * Constructor.
  41. *
  42. * @param LoggerInterface $logger A LoggerInterface instance
  43. */
  44. public function __construct(LoggerInterface $logger = null)
  45. {
  46. $this->logger = $logger;
  47. $this->supportsVariadic = method_exists('ReflectionParameter', 'isVariadic');
  48. $this->supportsScalarTypes = method_exists('ReflectionParameter', 'getType');
  49. }
  50. /**
  51. * {@inheritdoc}
  52. *
  53. * This method looks for a '_controller' request attribute that represents
  54. * the controller name (a string like ClassName::MethodName).
  55. */
  56. public function getController(Request $request)
  57. {
  58. if (!$controller = $request->attributes->get('_controller')) {
  59. if (null !== $this->logger) {
  60. $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.');
  61. }
  62. return false;
  63. }
  64. if (is_array($controller)) {
  65. return $controller;
  66. }
  67. if (is_object($controller)) {
  68. if (method_exists($controller, '__invoke')) {
  69. return $controller;
  70. }
  71. throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', get_class($controller), $request->getPathInfo()));
  72. }
  73. if (false === strpos($controller, ':')) {
  74. if (method_exists($controller, '__invoke')) {
  75. return $this->instantiateController($controller);
  76. } elseif (function_exists($controller)) {
  77. return $controller;
  78. }
  79. }
  80. $callable = $this->createController($controller);
  81. if (!is_callable($callable)) {
  82. throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable. %s', $request->getPathInfo(), $this->getControllerError($callable)));
  83. }
  84. return $callable;
  85. }
  86. /**
  87. * {@inheritdoc}
  88. *
  89. * @deprecated This method is deprecated as of 3.1 and will be removed in 4.0. Implement the ArgumentResolverInterface and inject it in the HttpKernel instead.
  90. */
  91. public function getArguments(Request $request, $controller)
  92. {
  93. @trigger_error(sprintf('%s is deprecated as of 3.1 and will be removed in 4.0. Implement the %s and inject it in the HttpKernel instead.', __METHOD__, ArgumentResolverInterface::class), E_USER_DEPRECATED);
  94. if (is_array($controller)) {
  95. $r = new \ReflectionMethod($controller[0], $controller[1]);
  96. } elseif (is_object($controller) && !$controller instanceof \Closure) {
  97. $r = new \ReflectionObject($controller);
  98. $r = $r->getMethod('__invoke');
  99. } else {
  100. $r = new \ReflectionFunction($controller);
  101. }
  102. return $this->doGetArguments($request, $controller, $r->getParameters());
  103. }
  104. /**
  105. * @param Request $request
  106. * @param callable $controller
  107. * @param \ReflectionParameter[] $parameters
  108. *
  109. * @return array The arguments to use when calling the action
  110. *
  111. * @deprecated This method is deprecated as of 3.1 and will be removed in 4.0. Implement the ArgumentResolverInterface and inject it in the HttpKernel instead.
  112. */
  113. protected function doGetArguments(Request $request, $controller, array $parameters)
  114. {
  115. @trigger_error(sprintf('%s is deprecated as of 3.1 and will be removed in 4.0. Implement the %s and inject it in the HttpKernel instead.', __METHOD__, ArgumentResolverInterface::class), E_USER_DEPRECATED);
  116. $attributes = $request->attributes->all();
  117. $arguments = array();
  118. foreach ($parameters as $param) {
  119. if (array_key_exists($param->name, $attributes)) {
  120. if ($this->supportsVariadic && $param->isVariadic() && is_array($attributes[$param->name])) {
  121. $arguments = array_merge($arguments, array_values($attributes[$param->name]));
  122. } else {
  123. $arguments[] = $attributes[$param->name];
  124. }
  125. } elseif ($param->getClass() && $param->getClass()->isInstance($request)) {
  126. $arguments[] = $request;
  127. } elseif ($param->isDefaultValueAvailable()) {
  128. $arguments[] = $param->getDefaultValue();
  129. } elseif ($this->supportsScalarTypes && $param->hasType() && $param->allowsNull()) {
  130. $arguments[] = null;
  131. } else {
  132. if (is_array($controller)) {
  133. $repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]);
  134. } elseif (is_object($controller)) {
  135. $repr = get_class($controller);
  136. } else {
  137. $repr = $controller;
  138. }
  139. throw new \RuntimeException(sprintf('Controller "%s" requires that you provide a value for the "$%s" argument (because there is no default value or because there is a non optional argument after this one).', $repr, $param->name));
  140. }
  141. }
  142. return $arguments;
  143. }
  144. /**
  145. * Returns a callable for the given controller.
  146. *
  147. * @param string $controller A Controller string
  148. *
  149. * @return callable A PHP callable
  150. *
  151. * @throws \InvalidArgumentException
  152. */
  153. protected function createController($controller)
  154. {
  155. if (false === strpos($controller, '::')) {
  156. throw new \InvalidArgumentException(sprintf('Unable to find controller "%s".', $controller));
  157. }
  158. list($class, $method) = explode('::', $controller, 2);
  159. if (!class_exists($class)) {
  160. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  161. }
  162. return array($this->instantiateController($class), $method);
  163. }
  164. /**
  165. * Returns an instantiated controller.
  166. *
  167. * @param string $class A class name
  168. *
  169. * @return object
  170. */
  171. protected function instantiateController($class)
  172. {
  173. return new $class();
  174. }
  175. private function getControllerError($callable)
  176. {
  177. if (is_string($callable)) {
  178. if (false !== strpos($callable, '::')) {
  179. $callable = explode('::', $callable);
  180. }
  181. if (class_exists($callable) && !method_exists($callable, '__invoke')) {
  182. return sprintf('Class "%s" does not have a method "__invoke".', $callable);
  183. }
  184. if (!function_exists($callable)) {
  185. return sprintf('Function "%s" does not exist.', $callable);
  186. }
  187. }
  188. if (!is_array($callable)) {
  189. return sprintf('Invalid type for controller given, expected string or array, got "%s".', gettype($callable));
  190. }
  191. if (2 !== count($callable)) {
  192. return sprintf('Invalid format for controller, expected array(controller, method) or controller::method.');
  193. }
  194. list($controller, $method) = $callable;
  195. if (is_string($controller) && !class_exists($controller)) {
  196. return sprintf('Class "%s" does not exist.', $controller);
  197. }
  198. $className = is_object($controller) ? get_class($controller) : $controller;
  199. if (method_exists($controller, $method)) {
  200. return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
  201. }
  202. $collection = get_class_methods($controller);
  203. $alternatives = array();
  204. foreach ($collection as $item) {
  205. $lev = levenshtein($method, $item);
  206. if ($lev <= strlen($method) / 3 || false !== strpos($item, $method)) {
  207. $alternatives[] = $item;
  208. }
  209. }
  210. asort($alternatives);
  211. $message = sprintf('Expected method "%s" on class "%s"', $method, $className);
  212. if (count($alternatives) > 0) {
  213. $message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives));
  214. } else {
  215. $message .= sprintf('. Available methods: "%s".', implode('", "', $collection));
  216. }
  217. return $message;
  218. }
  219. }