ControllerResolver.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 ControllerResolverInterface
  23. {
  24. private $logger;
  25. /**
  26. * Constructor.
  27. *
  28. * @param LoggerInterface $logger A LoggerInterface instance
  29. */
  30. public function __construct(LoggerInterface $logger = null)
  31. {
  32. $this->logger = $logger;
  33. }
  34. /**
  35. * {@inheritdoc}
  36. *
  37. * This method looks for a '_controller' request attribute that represents
  38. * the controller name (a string like ClassName::MethodName).
  39. */
  40. public function getController(Request $request)
  41. {
  42. if (!$controller = $request->attributes->get('_controller')) {
  43. if (null !== $this->logger) {
  44. $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.');
  45. }
  46. return false;
  47. }
  48. if (is_array($controller)) {
  49. return $controller;
  50. }
  51. if (is_object($controller)) {
  52. if (method_exists($controller, '__invoke')) {
  53. return $controller;
  54. }
  55. throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', get_class($controller), $request->getPathInfo()));
  56. }
  57. if (false === strpos($controller, ':')) {
  58. if (method_exists($controller, '__invoke')) {
  59. return $this->instantiateController($controller);
  60. } elseif (function_exists($controller)) {
  61. return $controller;
  62. }
  63. }
  64. $callable = $this->createController($controller);
  65. if (!is_callable($callable)) {
  66. throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable. %s', $request->getPathInfo(), $this->getControllerError($callable)));
  67. }
  68. return $callable;
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function getArguments(Request $request, $controller)
  74. {
  75. if (is_array($controller)) {
  76. $r = new \ReflectionMethod($controller[0], $controller[1]);
  77. } elseif (is_object($controller) && !$controller instanceof \Closure) {
  78. $r = new \ReflectionObject($controller);
  79. $r = $r->getMethod('__invoke');
  80. } else {
  81. $r = new \ReflectionFunction($controller);
  82. }
  83. return $this->doGetArguments($request, $controller, $r->getParameters());
  84. }
  85. protected function doGetArguments(Request $request, $controller, array $parameters)
  86. {
  87. $attributes = $request->attributes->all();
  88. $arguments = array();
  89. foreach ($parameters as $param) {
  90. if (array_key_exists($param->name, $attributes)) {
  91. if (PHP_VERSION_ID >= 50600 && $param->isVariadic() && is_array($attributes[$param->name])) {
  92. $arguments = array_merge($arguments, array_values($attributes[$param->name]));
  93. } else {
  94. $arguments[] = $attributes[$param->name];
  95. }
  96. } elseif ($param->getClass() && $param->getClass()->isInstance($request)) {
  97. $arguments[] = $request;
  98. } elseif ($param->isDefaultValueAvailable()) {
  99. $arguments[] = $param->getDefaultValue();
  100. } else {
  101. if (is_array($controller)) {
  102. $repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]);
  103. } elseif (is_object($controller)) {
  104. $repr = get_class($controller);
  105. } else {
  106. $repr = $controller;
  107. }
  108. 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));
  109. }
  110. }
  111. return $arguments;
  112. }
  113. /**
  114. * Returns a callable for the given controller.
  115. *
  116. * @param string $controller A Controller string
  117. *
  118. * @return callable A PHP callable
  119. *
  120. * @throws \InvalidArgumentException
  121. */
  122. protected function createController($controller)
  123. {
  124. if (false === strpos($controller, '::')) {
  125. throw new \InvalidArgumentException(sprintf('Unable to find controller "%s".', $controller));
  126. }
  127. list($class, $method) = explode('::', $controller, 2);
  128. if (!class_exists($class)) {
  129. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  130. }
  131. return array($this->instantiateController($class), $method);
  132. }
  133. /**
  134. * Returns an instantiated controller.
  135. *
  136. * @param string $class A class name
  137. *
  138. * @return object
  139. */
  140. protected function instantiateController($class)
  141. {
  142. return new $class();
  143. }
  144. private function getControllerError($callable)
  145. {
  146. if (is_string($callable)) {
  147. if (false !== strpos($callable, '::')) {
  148. $callable = explode('::', $callable);
  149. }
  150. if (class_exists($callable) && !method_exists($callable, '__invoke')) {
  151. return sprintf('Class "%s" does not have a method "__invoke".', $callable);
  152. }
  153. if (!function_exists($callable)) {
  154. return sprintf('Function "%s" does not exist.', $callable);
  155. }
  156. }
  157. if (!is_array($callable)) {
  158. return sprintf('Invalid type for controller given, expected string or array, got "%s".', gettype($callable));
  159. }
  160. if (2 !== count($callable)) {
  161. return sprintf('Invalid format for controller, expected array(controller, method) or controller::method.');
  162. }
  163. list($controller, $method) = $callable;
  164. if (is_string($controller) && !class_exists($controller)) {
  165. return sprintf('Class "%s" does not exist.', $controller);
  166. }
  167. $className = is_object($controller) ? get_class($controller) : $controller;
  168. if (method_exists($controller, $method)) {
  169. return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
  170. }
  171. $collection = get_class_methods($controller);
  172. $alternatives = array();
  173. foreach ($collection as $item) {
  174. $lev = levenshtein($method, $item);
  175. if ($lev <= strlen($method) / 3 || false !== strpos($item, $method)) {
  176. $alternatives[] = $item;
  177. }
  178. }
  179. asort($alternatives);
  180. $message = sprintf('Expected method "%s" on class "%s"', $method, $className);
  181. if (count($alternatives) > 0) {
  182. $message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives));
  183. } else {
  184. $message .= sprintf('. Available methods: "%s".', implode('", "', $collection));
  185. }
  186. return $message;
  187. }
  188. }