Passed
Push — master ( 9f67b1...4b575c )
by
unknown
01:31
created

Injector::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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