| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
/*
|
|
|
4 |
* This file is part of the Symfony package.
|
|
|
5 |
*
|
|
|
6 |
* (c) Fabien Potencier <fabien@symfony.com>
|
|
|
7 |
*
|
|
|
8 |
* For the full copyright and license information, please view the LICENSE
|
|
|
9 |
* file that was distributed with this source code.
|
|
|
10 |
*/
|
|
|
11 |
|
|
|
12 |
namespace Symfony\Component\HttpKernel\ControllerMetadata;
|
|
|
13 |
|
|
|
14 |
/**
|
|
|
15 |
* Builds {@see ArgumentMetadata} objects based on the given Controller.
|
|
|
16 |
*
|
|
|
17 |
* @author Iltar van der Berg <kjarli@gmail.com>
|
|
|
18 |
*/
|
|
|
19 |
final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface
|
|
|
20 |
{
|
|
|
21 |
public function createArgumentMetadata(string|object|array $controller, \ReflectionFunctionAbstract $reflector = null): array
|
|
|
22 |
{
|
|
|
23 |
$arguments = [];
|
|
|
24 |
$reflector ??= new \ReflectionFunction($controller(...));
|
|
|
25 |
|
|
|
26 |
foreach ($reflector->getParameters() as $param) {
|
|
|
27 |
$attributes = [];
|
|
|
28 |
foreach ($param->getAttributes() as $reflectionAttribute) {
|
|
|
29 |
if (class_exists($reflectionAttribute->getName())) {
|
|
|
30 |
$attributes[] = $reflectionAttribute->newInstance();
|
|
|
31 |
}
|
|
|
32 |
}
|
|
|
33 |
|
|
|
34 |
$arguments[] = new ArgumentMetadata($param->getName(), $this->getType($param), $param->isVariadic(), $param->isDefaultValueAvailable(), $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull(), $attributes);
|
|
|
35 |
}
|
|
|
36 |
|
|
|
37 |
return $arguments;
|
|
|
38 |
}
|
|
|
39 |
|
|
|
40 |
/**
|
|
|
41 |
* Returns an associated type to the given parameter if available.
|
|
|
42 |
*/
|
|
|
43 |
private function getType(\ReflectionParameter $parameter): ?string
|
|
|
44 |
{
|
|
|
45 |
if (!$type = $parameter->getType()) {
|
|
|
46 |
return null;
|
|
|
47 |
}
|
|
|
48 |
$name = $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type;
|
|
|
49 |
|
|
|
50 |
return match (strtolower($name)) {
|
|
|
51 |
'self' => $parameter->getDeclaringClass()?->name,
|
|
|
52 |
'parent' => get_parent_class($parameter->getDeclaringClass()?->name ?? '') ?: null,
|
|
|
53 |
default => $name,
|
|
|
54 |
};
|
|
|
55 |
}
|
|
|
56 |
}
|