Completed
Push — master ( 8ecded...ff0374 )
by Matthieu
11s
created

getParametersDefinition()   A

Complexity

Conditions 4
Paths 4

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 19
Code Lines 9

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 1
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace DI\Definition\Source;
4
5
use DI\Definition\AutowireDefinition;
6
use DI\Definition\EntryReference;
7
use DI\Definition\ObjectDefinition\MethodInjection;
8
9
/**
10
 * Reads DI class definitions using reflection.
11
 *
12
 * @author Matthieu Napoli <[email protected]>
13
 */
14
class ReflectionBasedAutowiring implements DefinitionSource, Autowiring
15
{
16
    public function autowire(string $name, AutowireDefinition $definition = null)
17
    {
18
        $className = $definition ? $definition->getClassName() : $name;
19
20
        if (!class_exists($className) && !interface_exists($className)) {
21
            return $definition;
22
        }
23
24
        $definition = $definition ?: new AutowireDefinition($name);
25
26
        // Constructor
27
        $class = new \ReflectionClass($className);
28
        $constructor = $class->getConstructor();
29
        if ($constructor && $constructor->isPublic()) {
30
            $constructorInjection = MethodInjection::constructor($this->getParametersDefinition($constructor));
31
            $definition->setDefaultConstructorInjection($constructorInjection);
32
        }
33
34
        return $definition;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function getDefinition($name)
41
    {
42
        return $this->autowire($name);
43
    }
44
45
    /**
46
     * Read the type-hinting from the parameters of the function.
47
     */
48
    private function getParametersDefinition(\ReflectionFunctionAbstract $constructor)
49
    {
50
        $parameters = [];
51
52
        foreach ($constructor->getParameters() as $index => $parameter) {
53
            // Skip optional parameters
54
            if ($parameter->isOptional()) {
55
                continue;
56
            }
57
58
            $parameterClass = $parameter->getClass();
59
60
            if ($parameterClass) {
61
                $parameters[$index] = new EntryReference($parameterClass->getName());
62
            }
63
        }
64
65
        return $parameters;
66
    }
67
}
68