Passed
Pull Request — master (#7)
by Alexander
01:28
created

Injector::make()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 2
dl 0
loc 13
ccs 8
cts 8
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Injector;
6
7
use Psr\Container\ContainerExceptionInterface;
8
use Psr\Container\ContainerInterface;
9
use Psr\Container\NotFoundExceptionInterface;
10
use ReflectionException;
11
12
/**
13
 * Injector is able to analyze callable dependencies based on
14
 * type hinting and inject them from any PSR-11 compatible container.
15
 */
16
final class Injector
17
{
18
    private ContainerInterface $container;
19
20 42
    public function __construct(ContainerInterface $container)
21
    {
22 42
        $this->container = $container;
23
    }
24
25
    /**
26
     * Invoke a callback with resolving dependencies based on parameter types.
27
     *
28
     * This methods allows invoking a callback and let type hinted parameter names to be
29
     * resolved as objects of the Container. It additionally allow calling function passing named arguments.
30
     *
31
     * For example, the following callback may be invoked using the Container to resolve the formatter dependency:
32
     *
33
     * ```php
34
     * $formatString = function($string, \Yiisoft\I18n\MessageFormatterInterface $formatter) {
35
     *    // ...
36
     * }
37
     *
38
     * $injector = new Yiisoft\Injector\Injector($container);
39
     * $injector->invoke($formatString, ['string' => 'Hello World!']);
40
     * ```
41
     *
42
     * This will pass the string `'Hello World!'` as the first argument, and a formatter instance created
43
     * by the DI container as the second argument.
44
     *
45
     * @param callable $callable callable to be invoked.
46
     * @param array $arguments The array of the function arguments.
47
     * This can be either a list of arguments, or an associative array where keys are argument names.
48
     * @return mixed the callable return value.
49
     * @throws MissingRequiredArgumentException if required argument is missing.
50
     * @throws ContainerExceptionInterface if a dependency cannot be resolved or if a dependency cannot be fulfilled.
51
     * @throws ReflectionException
52
     */
53 31
    public function invoke(callable $callable, array $arguments = [])
54
    {
55 31
        $callable = \Closure::fromCallable($callable);
56 31
        $reflection = new \ReflectionFunction($callable);
57 31
        return $reflection->invokeArgs($this->resolveDependencies($reflection, $arguments));
58
    }
59
60
    /**
61
     * Creates an object of a given class with resolving constructor dependencies based on parameter types.
62
     *
63
     * This methods allows invoking a constructor and let type hinted parameter names to be
64
     * resolved as objects of the Container. It additionally allow calling constructor passing named arguments.
65
     *
66
     * For example, the following constructor may be invoked using the Container to resolve the formatter dependency:
67
     *
68
     * ```php
69
     * class StringFormatter
70
     * {
71
     *     public function __construct($string, \Yiisoft\I18n\MessageFormatterInterface $formatter)
72
     *     {
73
     *         // ...
74
     *     }
75
     * }
76
     *
77
     * $injector = new Yiisoft\Injector\Injector($container);
78
     * $stringFormatter = $injector->make(StringFormatter::class, ['string' => 'Hello World!']);
79
     * ```
80
     *
81
     * This will pass the string `'Hello World!'` as the first argument, and a formatter instance created
82
     * by the DI container as the second argument.
83
     *
84
     * @param string $class name of the class to be created.
85
     * @param array $arguments The array of the function arguments.
86
     * This can be either a list of arguments, or an associative array where keys are argument names.
87
     * @return mixed object of the given class.
88
     * @throws ContainerExceptionInterface
89
     * @throws MissingRequiredArgumentException|InvalidArgumentException
90
     * @throws ReflectionException
91
     */
92 11
    public function make(string $class, array $arguments = [])
93
    {
94 11
        $classReflection = new \ReflectionClass($class);
95 10
        if (!$classReflection->isInstantiable()) {
96 3
            throw new \InvalidArgumentException("Class $class is not instantiable.");
97
        }
98 7
        $reflection = $classReflection->getConstructor();
99 7
        if ($reflection === null) {
100
            // Method __construct() does not exist
101 1
            return new $class();
102
        }
103
104 6
        return new $class(...$this->resolveDependencies($reflection, $arguments));
105
    }
106
107
    /**
108
     * Resolve dependencies for the given function reflection object and a list of concrete arguments
109
     * and return array of arguments to call the function with.
110
     *
111
     * @param \ReflectionFunctionAbstract $reflection function reflection.
112
     * @param array $arguments concrete arguments.
113
     * @return array resolved arguments.
114
     * @throws ContainerExceptionInterface
115
     * @throws MissingRequiredArgumentException|InvalidArgumentException
116
     * @throws ReflectionException
117
     */
118 37
    private function resolveDependencies(\ReflectionFunctionAbstract $reflection, array $arguments = []): array
119
    {
120 37
        $resolvedArguments = [];
121
122 37
        $pushUnusedArguments = true;
123 37
        foreach ($reflection->getParameters() as $parameter) {
124 32
            $name = $parameter->getName();
125 32
            $class = $parameter->getClass();
126 32
            $hasType = $parameter->hasType();
127 32
            $isNullable = $parameter->allowsNull() && $hasType;
128 32
            $isVariadic = $parameter->isVariadic();
129 32
            $error = null;
130
            unset($tmpValue);
131
132 32
            // Get argument by name
133 6
            if (array_key_exists($name, $arguments)) {
134 1
                if ($isVariadic && is_array($arguments[$name])) {
135
                    $resolvedArguments = array_merge($resolvedArguments, array_values($arguments[$name]));
136 5
                } else {
137
                    $resolvedArguments[] = &$arguments[$name];
138 6
                }
139 6
                unset($arguments[$name]);
140
                continue;
141
            }
142 29
143 29
            $type = $hasType ? $parameter->getType()->getName() : null;
144
            if ($class !== null || $type === 'object') {
145 21
                // Unnamed arguments
146 21
                $className = $class !== null ? $class->getName() : null;
147 21
                $found = false;
148 9
                foreach ($arguments as $key => $item) {
149 1
                    if (!is_int($key)) {
150
                        continue;
151 8
                    }
152 7
                    if (is_object($item) and $className === null || $item instanceof $className) {
153 7
                        $found = true;
154 7
                        $resolvedArguments[] = &$arguments[$key];
155 7
                        unset($arguments[$key], $item);
156 5
                        if (!$isVariadic) {
157
                            break;
158
                        }
159
                    }
160 21
                }
161 7
                if ($found) {
162 7
                    $pushUnusedArguments = false;
163
                    continue;
164
                }
165 18
166
                if ($className !== null) {
167
                    // If the argument is optional we catch not instantiable exceptions
168 17
                    try {
169 15
                        $tmpValue = $this->container->get($className);
170 3
                        $resolvedArguments[] = &$tmpValue;
171 3
                        continue;
172
                    } catch (NotFoundExceptionInterface $e) {
173
                        $error = $e;
174
                    }
175
                }
176 15
            }
177 2
178 13
            if ($parameter->isDefaultValueAvailable()) {
179 9
                $tmpValue = $parameter->getDefaultValue();
180 2
                $resolvedArguments[] = &$tmpValue;
181
            } elseif (!$parameter->isOptional()) {
182 9
                if ($isNullable) {
183
                    $tmpValue = null;
184 4
                    $resolvedArguments[] = &$tmpValue;
185 2
                } else {
186
                    throw $error ?? new MissingRequiredArgumentException($name, $reflection->getName());
187
                }
188
            } elseif ($hasType) {
189 30
                $pushUnusedArguments = false;
190 7
            }
191 7
        }
192 2
193
        foreach ($arguments as $key => $value) {
194 5
            if (is_int($key)) {
195 2
                if (!is_object($value)) {
196
                    throw new InvalidArgumentException((string)$key, $reflection->getName());
197
                }
198
                if ($pushUnusedArguments) {
199 28
                    $resolvedArguments[] = $value;
200
                }
201
            }
202
        }
203
        return $resolvedArguments;
204
    }
205
}
206