-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
ControllerResolver.php
272 lines (216 loc) · 9.49 KB
/
ControllerResolver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Attribute\AsController;
/**
* This implementation uses the '_controller' request attribute to determine
* the controller to execute.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Tobias Schultze <http://tobion.de>
*/
class ControllerResolver implements ControllerResolverInterface
{
private array $allowedControllerTypes = [];
private array $allowedControllerAttributes = [AsController::class => AsController::class];
public function __construct(
private ?LoggerInterface $logger = null,
) {
}
/**
* @param array<class-string> $types
* @param array<class-string> $attributes
*/
public function allowControllers(array $types = [], array $attributes = []): void
{
foreach ($types as $type) {
$this->allowedControllerTypes[$type] = $type;
}
foreach ($attributes as $attribute) {
$this->allowedControllerAttributes[$attribute] = $attribute;
}
}
/**
* @throws BadRequestException when the request has attribute "_check_controller_is_allowed" set to true and the controller is not allowed
*/
public function getController(Request $request): callable|false
{
if (!$controller = $request->attributes->get('_controller')) {
$this->logger?->warning('Unable to look for the controller as the "_controller" parameter is missing.');
return false;
}
if (\is_array($controller)) {
if (isset($controller[0]) && \is_string($controller[0]) && isset($controller[1])) {
try {
$controller[0] = $this->instantiateController($controller[0]);
} catch (\Error|\LogicException $e) {
if (\is_callable($controller)) {
return $this->checkController($request, $controller);
}
throw $e;
}
}
if (!\is_callable($controller)) {
throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
}
return $this->checkController($request, $controller);
}
if (\is_object($controller)) {
if (!\is_callable($controller)) {
throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
}
return $this->checkController($request, $controller);
}
if (\function_exists($controller)) {
return $this->checkController($request, $controller);
}
try {
$callable = $this->createController($controller);
} catch (\InvalidArgumentException $e) {
throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$e->getMessage(), 0, $e);
}
if (!\is_callable($callable)) {
throw new \InvalidArgumentException(\sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($callable));
}
return $this->checkController($request, $callable);
}
/**
* Returns a callable for the given controller.
*
* @throws \InvalidArgumentException When the controller cannot be created
*/
protected function createController(string $controller): callable
{
if (!str_contains($controller, '::')) {
$controller = $this->instantiateController($controller);
if (!\is_callable($controller)) {
throw new \InvalidArgumentException($this->getControllerError($controller));
}
return $controller;
}
[$class, $method] = explode('::', $controller, 2);
try {
$controller = [$this->instantiateController($class), $method];
} catch (\Error|\LogicException $e) {
try {
if ((new \ReflectionMethod($class, $method))->isStatic()) {
return $class.'::'.$method;
}
} catch (\ReflectionException) {
throw $e;
}
throw $e;
}
if (!\is_callable($controller)) {
throw new \InvalidArgumentException($this->getControllerError($controller));
}
return $controller;
}
/**
* Returns an instantiated controller.
*/
protected function instantiateController(string $class): object
{
return new $class();
}
private function getControllerError(mixed $callable): string
{
if (\is_string($callable)) {
if (str_contains($callable, '::')) {
$callable = explode('::', $callable, 2);
} else {
return \sprintf('Function "%s" does not exist.', $callable);
}
}
if (\is_object($callable)) {
$availableMethods = $this->getClassMethodsWithoutMagicMethods($callable);
$alternativeMsg = $availableMethods ? \sprintf(' or use one of the available methods: "%s"', implode('", "', $availableMethods)) : '';
return \sprintf('Controller class "%s" cannot be called without a method name. You need to implement "__invoke"%s.', get_debug_type($callable), $alternativeMsg);
}
if (!\is_array($callable)) {
return \sprintf('Invalid type for controller given, expected string, array or object, got "%s".', get_debug_type($callable));
}
if (!isset($callable[0]) || !isset($callable[1]) || 2 !== \count($callable)) {
return 'Invalid array callable, expected [controller, method].';
}
[$controller, $method] = $callable;
if (\is_string($controller) && !class_exists($controller)) {
return \sprintf('Class "%s" does not exist.', $controller);
}
$className = \is_object($controller) ? get_debug_type($controller) : $controller;
if (method_exists($controller, $method)) {
return \sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
}
$collection = $this->getClassMethodsWithoutMagicMethods($controller);
$alternatives = [];
foreach ($collection as $item) {
$lev = levenshtein($method, $item);
if ($lev <= \strlen($method) / 3 || str_contains($item, $method)) {
$alternatives[] = $item;
}
}
asort($alternatives);
$message = \sprintf('Expected method "%s" on class "%s"', $method, $className);
if (\count($alternatives) > 0) {
$message .= \sprintf(', did you mean "%s"?', implode('", "', $alternatives));
} else {
$message .= \sprintf('. Available methods: "%s".', implode('", "', $collection));
}
return $message;
}
private function getClassMethodsWithoutMagicMethods($classOrObject): array
{
$methods = get_class_methods($classOrObject);
return array_filter($methods, fn (string $method) => 0 !== strncmp($method, '__', 2));
}
private function checkController(Request $request, callable $controller): callable
{
if (!$request->attributes->get('_check_controller_is_allowed', false)) {
return $controller;
}
$r = null;
if (\is_array($controller)) {
[$class, $name] = $controller;
$name = (\is_string($class) ? $class : $class::class).'::'.$name;
} elseif (\is_object($controller) && !$controller instanceof \Closure) {
$class = $controller;
$name = $class::class.'::__invoke';
} else {
$r = new \ReflectionFunction($controller);
$name = $r->name;
if ($r->isAnonymous()) {
$name = $class = \Closure::class;
} elseif ($class = $r->getClosureCalledClass()) {
$class = $class->name;
$name = $class.'::'.$name;
}
}
if ($class) {
foreach ($this->allowedControllerTypes as $type) {
if (is_a($class, $type, true)) {
return $controller;
}
}
}
$r ??= new \ReflectionClass($class);
foreach ($r->getAttributes() as $attribute) {
if (isset($this->allowedControllerAttributes[$attribute->getName()])) {
return $controller;
}
}
if (str_contains($name, '@anonymous')) {
$name = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $name);
}
throw new BadRequestException(\sprintf('Callable "%s()" is not allowed as a controller. Did you miss tagging it with "#[AsController]" or registering its type with "%s::allowControllers()"?', $name, self::class));
}
}