DefinitionExtractor   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 53
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A fromFunction() 0 7 2
A fromClassName() 0 21 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Definitions\Helpers;
6
7
use ReflectionClass;
8
use ReflectionException;
9
use ReflectionFunctionAbstract;
10
use Yiisoft\Definitions\Exception\NotInstantiableClassException;
11
use Yiisoft\Definitions\Exception\NotInstantiableException;
12
use Yiisoft\Definitions\ParameterDefinition;
13
14
/**
15
 * This class extracts dependency definitions from type hints of a function or a class constructor parameters.
16
 * Note that service names need not match the parameter names, parameter names are ignored.
17
 *
18
 * @internal
19
 */
20
final class DefinitionExtractor
21
{
22
    /**
23
     * @psalm-var array<string, array<string, ParameterDefinition>>
24
     */
25
    private static array $dependencies = [];
26
27
    /**
28
     * Extract dependency definitions from type hints of a class constructor parameters.
29
     *
30
     * @psalm-param class-string $class
31
     *
32
     * @throws NotInstantiableException
33
     *
34
     * @return ParameterDefinition[]
35
     * @psalm-return array<string, ParameterDefinition>
36
     */
37 74
    public static function fromClassName(string $class): array
38
    {
39 74
        if (isset(self::$dependencies[$class])) {
40 45
            return self::$dependencies[$class];
41
        }
42
43
        try {
44 30
            $reflectionClass = new ReflectionClass($class);
45 1
        } catch (ReflectionException) {
46 1
            throw new NotInstantiableClassException($class);
47
        }
48
49 29
        if (!$reflectionClass->isInstantiable()) {
50 4
            throw new NotInstantiableClassException($class);
51
        }
52
53 27
        $constructor = $reflectionClass->getConstructor();
54 27
        $dependencies = $constructor === null ? [] : self::fromFunction($constructor);
55 27
        self::$dependencies[$class] = $dependencies;
56
57 27
        return $dependencies;
58
    }
59
60
    /**
61
     * Extract dependency definitions from type hints of a function.
62
     *
63
     * @return ParameterDefinition[]
64
     * @psalm-return array<string, ParameterDefinition>
65
     */
66 52
    public static function fromFunction(ReflectionFunctionAbstract $reflectionFunction): array
67
    {
68 52
        $result = [];
69 52
        foreach ($reflectionFunction->getParameters() as $parameter) {
70 51
            $result[$parameter->getName()] = new ParameterDefinition($parameter);
71
        }
72 52
        return $result;
73
    }
74
}
75