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;
18 * This implementation uses the '_controller' request attribute to determine
19 * the controller to execute and uses the request attributes to determine
20 * the controller method arguments.
22 * @author Fabien Potencier <fabien@symfony.com>
24 class ControllerResolver implements ArgumentResolverInterface, ControllerResolverInterface
29 * If the ...$arg functionality is available.
31 * Requires at least PHP 5.6.0 or HHVM 3.9.1
35 private $supportsVariadic;
38 * If scalar types exists.
42 private $supportsScalarTypes;
44 public function __construct(LoggerInterface $logger = null)
46 $this->logger = $logger;
48 $this->supportsVariadic = method_exists('ReflectionParameter', 'isVariadic');
49 $this->supportsScalarTypes = method_exists('ReflectionParameter', 'getType');
55 * This method looks for a '_controller' request attribute that represents
56 * the controller name (a string like ClassName::MethodName).
58 public function getController(Request $request)
60 if (!$controller = $request->attributes->get('_controller')) {
61 if (null !== $this->logger) {
62 $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.');
68 if (\is_array($controller)) {
72 if (\is_object($controller)) {
73 if (method_exists($controller, '__invoke')) {
77 throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', \get_class($controller), $request->getPathInfo()));
80 if (false === strpos($controller, ':')) {
81 if (method_exists($controller, '__invoke')) {
82 return $this->instantiateController($controller);
83 } elseif (\function_exists($controller)) {
88 $callable = $this->createController($controller);
90 if (!\is_callable($callable)) {
91 throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable. %s', $request->getPathInfo(), $this->getControllerError($callable)));
100 * @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.
102 public function getArguments(Request $request, $controller)
104 @trigger_error(sprintf('The "%s()" method 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);
106 if (\is_array($controller)) {
107 $r = new \ReflectionMethod($controller[0], $controller[1]);
108 } elseif (\is_object($controller) && !$controller instanceof \Closure) {
109 $r = new \ReflectionObject($controller);
110 $r = $r->getMethod('__invoke');
112 $r = new \ReflectionFunction($controller);
115 return $this->doGetArguments($request, $controller, $r->getParameters());
119 * @param Request $request
120 * @param callable $controller
121 * @param \ReflectionParameter[] $parameters
123 * @return array The arguments to use when calling the action
125 * @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.
127 protected function doGetArguments(Request $request, $controller, array $parameters)
129 @trigger_error(sprintf('The "%s()" method 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);
131 $attributes = $request->attributes->all();
132 $arguments = array();
133 foreach ($parameters as $param) {
134 if (array_key_exists($param->name, $attributes)) {
135 if ($this->supportsVariadic && $param->isVariadic() && \is_array($attributes[$param->name])) {
136 $arguments = array_merge($arguments, array_values($attributes[$param->name]));
138 $arguments[] = $attributes[$param->name];
140 } elseif ($param->getClass() && $param->getClass()->isInstance($request)) {
141 $arguments[] = $request;
142 } elseif ($param->isDefaultValueAvailable()) {
143 $arguments[] = $param->getDefaultValue();
144 } elseif ($this->supportsScalarTypes && $param->hasType() && $param->allowsNull()) {
147 if (\is_array($controller)) {
148 $repr = sprintf('%s::%s()', \get_class($controller[0]), $controller[1]);
149 } elseif (\is_object($controller)) {
150 $repr = \get_class($controller);
155 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));
163 * Returns a callable for the given controller.
165 * @param string $controller A Controller string
167 * @return callable A PHP callable
169 * @throws \InvalidArgumentException
171 protected function createController($controller)
173 if (false === strpos($controller, '::')) {
174 throw new \InvalidArgumentException(sprintf('Unable to find controller "%s".', $controller));
177 list($class, $method) = explode('::', $controller, 2);
179 if (!class_exists($class)) {
180 throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
183 return array($this->instantiateController($class), $method);
187 * Returns an instantiated controller.
189 * @param string $class A class name
193 protected function instantiateController($class)
198 private function getControllerError($callable)
200 if (\is_string($callable)) {
201 if (false !== strpos($callable, '::')) {
202 $callable = explode('::', $callable);
205 if (class_exists($callable) && !method_exists($callable, '__invoke')) {
206 return sprintf('Class "%s" does not have a method "__invoke".', $callable);
209 if (!\function_exists($callable)) {
210 return sprintf('Function "%s" does not exist.', $callable);
214 if (!\is_array($callable)) {
215 return sprintf('Invalid type for controller given, expected string or array, got "%s".', \gettype($callable));
218 if (2 !== \count($callable)) {
219 return 'Invalid format for controller, expected array(controller, method) or controller::method.';
222 list($controller, $method) = $callable;
224 if (\is_string($controller) && !class_exists($controller)) {
225 return sprintf('Class "%s" does not exist.', $controller);
228 $className = \is_object($controller) ? \get_class($controller) : $controller;
230 if (method_exists($controller, $method)) {
231 return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
234 $collection = get_class_methods($controller);
236 $alternatives = array();
238 foreach ($collection as $item) {
239 $lev = levenshtein($method, $item);
241 if ($lev <= \strlen($method) / 3 || false !== strpos($item, $method)) {
242 $alternatives[] = $item;
246 asort($alternatives);
248 $message = sprintf('Expected method "%s" on class "%s"', $method, $className);
250 if (\count($alternatives) > 0) {
251 $message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives));
253 $message .= sprintf('. Available methods: "%s".', implode('", "', $collection));