generated from yiisoft/package-template
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
DefinitionExtractor.php
74 lines (64 loc) · 2.19 KB
/
DefinitionExtractor.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
<?php
declare(strict_types=1);
namespace Yiisoft\Definitions\Helpers;
use ReflectionClass;
use ReflectionException;
use ReflectionFunctionAbstract;
use Yiisoft\Definitions\Exception\NotInstantiableClassException;
use Yiisoft\Definitions\Exception\NotInstantiableException;
use Yiisoft\Definitions\ParameterDefinition;
/**
* This class extracts dependency definitions from type hints of a function or a class constructor parameters.
* Note that service names need not match the parameter names, parameter names are ignored.
*
* @internal
*/
final class DefinitionExtractor
{
/**
* @psalm-var array<string, array<string, ParameterDefinition>>
*/
private static array $dependencies = [];
/**
* Extract dependency definitions from type hints of a class constructor parameters.
*
* @psalm-param class-string $class
*
* @throws NotInstantiableException
*
* @return ParameterDefinition[]
* @psalm-return array<string, ParameterDefinition>
*/
public static function fromClassName(string $class): array
{
if (isset(self::$dependencies[$class])) {
return self::$dependencies[$class];
}
try {
$reflectionClass = new ReflectionClass($class);
} catch (ReflectionException) {
throw new NotInstantiableClassException($class);
}
if (!$reflectionClass->isInstantiable()) {
throw new NotInstantiableClassException($class);
}
$constructor = $reflectionClass->getConstructor();
$dependencies = $constructor === null ? [] : self::fromFunction($constructor);
self::$dependencies[$class] = $dependencies;
return $dependencies;
}
/**
* Extract dependency definitions from type hints of a function.
*
* @return ParameterDefinition[]
* @psalm-return array<string, ParameterDefinition>
*/
public static function fromFunction(ReflectionFunctionAbstract $reflectionFunction): array
{
$result = [];
foreach ($reflectionFunction->getParameters() as $parameter) {
$result[$parameter->getName()] = new ParameterDefinition($parameter);
}
return $result;
}
}