Passed
Pull Request — master (#81)
by Evgeniy
03:11
created

Reflection   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 53
rs 10
c 0
b 0
f 0
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getDependencies() 0 6 2
A getMethodParameters() 0 10 4
A load() 0 9 2
A isInstantiable() 0 6 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cekta\DI;
6
7
use ReflectionClass;
8
use ReflectionException;
9
use ReflectionMethod;
10
11
class Reflection
12
{
13
    private static $dependencies = [];
14
    private static $instantiable = [];
15
16
    /**
17
     * @param string $name
18
     * @return array<string>
19
     * @internal
20
     */
21
    public function getDependencies(string $name): array
22
    {
23
        if (!array_key_exists($name, self::$dependencies)) {
24
            $this->load($name);
25
        }
26
        return self::$dependencies[$name];
27
    }
28
29
    /**
30
     * @param string $name
31
     * @return bool
32
     * @internal
33
     */
34
    public function isInstantiable(string $name): bool
35
    {
36
        if (!array_key_exists($name, self::$instantiable)) {
37
            $this->load($name);
38
        }
39
        return self::$instantiable[$name];
40
    }
41
42
    private function load(string $name): void
43
    {
44
        try {
45
            $class = new ReflectionClass($name);
46
            self::$instantiable[$name] = $class->isInstantiable();
47
            self::$dependencies[$name] = self::getMethodParameters($class->getConstructor());
48
        } catch (ReflectionException $exception) {
49
            self::$dependencies[$name] = [];
50
            self::$instantiable[$name] = false;
51
        }
52
    }
53
54
    private static function getMethodParameters(?ReflectionMethod $method): array
55
    {
56
        $result = [];
57
        if ($method !== null) {
58
            foreach ($method->getParameters() as $parameter) {
59
                $class = $parameter->getClass();
60
                $result[] = $class ? $class->name : $parameter->name;
61
            }
62
        }
63
        return $result;
64
    }
65
}
66