Passed
Push — master ( 8afadc...1cb41c )
by Alexander
03:09 queued 54s
created

DefinitionExtractor::fromClassName()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 5
nop 1
dl 0
loc 21
ccs 12
cts 12
cp 1
crap 5
rs 9.5555
c 0
b 0
f 0
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 36
    public static function fromClassName(string $class): array
38
    {
39 36
        if (isset(self::$dependencies[$class])) {
40 18
            return self::$dependencies[$class];
41
        }
42
43
        try {
44 19
            $reflectionClass = new ReflectionClass($class);
45 1
        } catch (ReflectionException $e) {
46 1
            throw new NotInstantiableClassException($class);
47
        }
48
49 18
        if (!$reflectionClass->isInstantiable()) {
50 3
            throw new NotInstantiableClassException($class);
51
        }
52
53 16
        $constructor = $reflectionClass->getConstructor();
54 16
        $dependencies = $constructor === null ? [] : self::fromFunction($constructor);
55 16
        self::$dependencies[$class] = $dependencies;
56
57 16
        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 20
    public static function fromFunction(ReflectionFunctionAbstract $reflectionFunction): array
67
    {
68 20
        $result = [];
69 20
        foreach ($reflectionFunction->getParameters() as $parameter) {
70 20
            $result[$parameter->getName()] = new ParameterDefinition($parameter);
71
        }
72 20
        return $result;
73
    }
74
}
75