4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel\Controller;
14 use Psr\Log\LoggerInterface;
15 use Symfony\Component\HttpFoundation\Request;
20 * This implementation uses the '_controller' request attribute to determine
21 * the controller to execute and uses the request attributes to determine
22 * the controller method arguments.
24 * @author Fabien Potencier <fabien@symfony.com>
26 class ControllerResolver implements ArgumentResolverInterface, ControllerResolverInterface
31 * If the ...$arg functionality is available.
33 * Requires at least PHP 5.6.0 or HHVM 3.9.1
37 private $supportsVariadic;
40 * If scalar types exists.
44 private $supportsScalarTypes;
49 * @param LoggerInterface $logger A LoggerInterface instance
51 public function __construct(LoggerInterface $logger = null)
53 $this->logger = $logger;
55 $this->supportsVariadic = method_exists('ReflectionParameter', 'isVariadic');
56 $this->supportsScalarTypes = method_exists('ReflectionParameter', 'getType');
62 * This method looks for a '_controller' request attribute that represents
63 * the controller name (a string like ClassName::MethodName).
65 public function getController(Request $request)
67 if (!$controller = $request->attributes->get('_controller')) {
68 if (null !== $this->logger) {
69 $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.');
75 if (is_array($controller)) {
79 if (is_object($controller)) {
80 if (method_exists($controller, '__invoke')) {
84 throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', get_class($controller), $request->getPathInfo()));
87 if (false === strpos($controller, ':')) {
88 if (method_exists($controller, '__invoke')) {
89 return $this->instantiateController($controller);
90 } elseif (function_exists($controller)) {
95 $callable = $this->createController($controller);
97 if (!is_callable($callable)) {
98 throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable. %s', $request->getPathInfo(), $this->getControllerError($callable)));
107 * @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.
109 public function getArguments(Request $request, $controller)
111 @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);
113 if (is_array($controller)) {
114 $r = new \ReflectionMethod($controller[0], $controller[1]);
115 } elseif (is_object($controller) && !$controller instanceof \Closure) {
116 $r = new \ReflectionObject($controller);
117 $r = $r->getMethod('__invoke');
119 $r = new \ReflectionFunction($controller);
122 return $this->doGetArguments($request, $controller, $r->getParameters());
126 * @param Request $request
127 * @param callable $controller
128 * @param \ReflectionParameter[] $parameters
130 * @return array The arguments to use when calling the action
132 * @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.
134 protected function doGetArguments(Request $request, $controller, array $parameters)
136 @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);
138 $attributes = $request->attributes->all();
139 $arguments = array();
140 foreach ($parameters as $param) {
141 if (array_key_exists($param->name, $attributes)) {
142 if ($this->supportsVariadic && $param->isVariadic() && is_array($attributes[$param->name])) {
143 $arguments = array_merge($arguments, array_values($attributes[$param->name]));
145 $arguments[] = $attributes[$param->name];
147 } elseif ($param->getClass() && $param->getClass()->isInstance($request)) {
148 $arguments[] = $request;
149 } elseif ($param->isDefaultValueAvailable()) {
150 $arguments[] = $param->getDefaultValue();
151 } elseif ($this->supportsScalarTypes && $param->hasType() && $param->allowsNull()) {
154 if (is_array($controller)) {
155 $repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]);
156 } elseif (is_object($controller)) {
157 $repr = get_class($controller);
162 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));
170 * Returns a callable for the given controller.
172 * @param string $controller A Controller string
174 * @return callable A PHP callable
176 * @throws \InvalidArgumentException
178 protected function createController($controller)
180 if (false === strpos($controller, '::')) {
181 throw new \InvalidArgumentException(sprintf('Unable to find controller "%s".', $controller));
184 list($class, $method) = explode('::', $controller, 2);
186 if (!class_exists($class)) {
187 throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
190 return array($this->instantiateController($class), $method);
194 * Returns an instantiated controller.
196 * @param string $class A class name
200 protected function instantiateController($class)
205 private function getControllerError($callable)
207 if (is_string($callable)) {
208 if (false !== strpos($callable, '::')) {
209 $callable = explode('::', $callable);
212 if (class_exists($callable) && !method_exists($callable, '__invoke')) {
213 return sprintf('Class "%s" does not have a method "__invoke".', $callable);
216 if (!function_exists($callable)) {
217 return sprintf('Function "%s" does not exist.', $callable);
221 if (!is_array($callable)) {
222 return sprintf('Invalid type for controller given, expected string or array, got "%s".', gettype($callable));
225 if (2 !== count($callable)) {
226 return sprintf('Invalid format for controller, expected array(controller, method) or controller::method.');
229 list($controller, $method) = $callable;
231 if (is_string($controller) && !class_exists($controller)) {
232 return sprintf('Class "%s" does not exist.', $controller);
235 $className = is_object($controller) ? get_class($controller) : $controller;
237 if (method_exists($controller, $method)) {
238 return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
241 $collection = get_class_methods($controller);
243 $alternatives = array();
245 foreach ($collection as $item) {
246 $lev = levenshtein($method, $item);
248 if ($lev <= strlen($method) / 3 || false !== strpos($item, $method)) {
249 $alternatives[] = $item;
253 asort($alternatives);
255 $message = sprintf('Expected method "%s" on class "%s"', $method, $className);
257 if (count($alternatives) > 0) {
258 $message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives));
260 $message .= sprintf('. Available methods: "%s".', implode('", "', $collection));