Completed
Push — sam-rework ( 1696e6 )
by Andrii
38:13 queued 23:11
created

ClassNameResolver::resolveParameter()   B

Complexity

Conditions 9
Paths 15

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 16
rs 8.0555
c 0
b 0
f 0
cc 9
nc 15
nop 1
1
<?php
2
3
4
namespace yii\di\resolvers;
5
6
use yii\di\contracts\DependencyInterface;
7
use yii\di\contracts\DependencyResolverInterface;
8
use yii\di\dependencies\ClassDependency;
9
use yii\di\dependencies\InvalidDependency;
10
use yii\di\dependencies\ValueDependency;
11
use yii\di\exceptions\NotInstantiableException;
12
13
/**
14
 * Class ClassNameResolver
15
 * This implementation resolves dependencies by using class type hints.
16
 * Note that service names need not match the parameter names, parameter names are ignored
17
 */
18
class ClassNameResolver implements DependencyResolverInterface
19
{
20
21
    /**
22
     * @inheritdoc
23
     */
24
    public function resolveConstructor(string $class): array
25
    {
26
        $reflectionClass = new \ReflectionClass($class);
27
        if (!$reflectionClass->isInstantiable()) {
28
            throw new NotInstantiableException($class);
29
        }
30
        $constructor = $reflectionClass->getConstructor();
31
        return $constructor === null ? [] : $this->resolveFunction($constructor);
32
    }
33
34
    private function resolveFunction(\ReflectionFunctionAbstract $reflectionFunction): array
35
    {
36
        $result = [];
37
        foreach ($reflectionFunction->getParameters() as $parameter) {
38
            $result[] = $this->resolveParameter($parameter);
39
        }
40
        return $result;
41
    }
42
43
    private function resolveParameter(\ReflectionParameter $parameter): DependencyInterface
44
    {
45
        $type = $parameter->getType();
46
        $hasDefault = $parameter->isOptional() || $parameter->isDefaultValueAvailable() || (isset($type) && $type->allowsNull());
47
48
        if (!$hasDefault && $type === null) {
49
            return new InvalidDependency();
50
        }
51
52
        // Our parameter has a class type hint
53
        if ($type !== null && !$type->isBuiltin()) {
54
            return new ClassDependency($type->getName(), $type->allowsNull());
55
        }
56
57
        // Our parameter does not have a class type hint and either has a default value or is nullable.
58
        return new ValueDependency($parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null);
59
    }
60
61
    /**
62
     * @inheritdoc
63
     */
64
    public function resolveCallable(callable $callable): array
65
    {
66
        return $this->resolveFunction(new \ReflectionFunction(\Closure::fromCallable($callable)));
67
    }
68
}
69