Passed
Pull Request — master (#35)
by Wilmer
17:45 queued 04:49
created

ParameterDefinition::isBuiltin()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Definitions;
6
7
use Psr\Container\ContainerInterface;
8
use ReflectionNamedType;
9
use ReflectionParameter;
10
use ReflectionUnionType;
11
use Throwable;
12
use Yiisoft\Definitions\Contract\DefinitionInterface;
13
use Yiisoft\Definitions\Exception\CircularReferenceException;
14
use Yiisoft\Definitions\Exception\NotInstantiableException;
15
use Yiisoft\Definitions\Exception\InvalidConfigException;
16
17
use function get_class;
18
use function gettype;
19
use function is_object;
20
21
/**
22
 * Parameter definition resolves an object based on information from `ReflectionParameter` instance.
23
 */
24
final class ParameterDefinition implements DefinitionInterface
25
{
26
    private ReflectionParameter $parameter;
27
28 54
    public function __construct(ReflectionParameter $parameter)
29
    {
30 54
        $this->parameter = $parameter;
31
    }
32
33 13
    public function getReflection(): ReflectionParameter
34
    {
35 13
        return $this->parameter;
36
    }
37
38 56
    public function isVariadic(): bool
39
    {
40 56
        return $this->parameter->isVariadic();
41
    }
42
43 25
    public function isOptional(): bool
44
    {
45 25
        return $this->parameter->isOptional();
46
    }
47
48 42
    public function isBuiltin(): bool
49
    {
50 42
        $type = $this->parameter->getType();
51 42
        if ($type === null) {
52 1
            return false;
53
        }
54 41
        return $type->isBuiltin();
55
    }
56
57 20
    public function hasValue(): bool
58
    {
59 20
        return $this->parameter->isDefaultValueAvailable();
60
    }
61
62 49
    public function resolve(ContainerInterface $container)
63
    {
64 49
        $type = $this->parameter->getType();
65
66 49
        if ($type === null || $this->isVariadic()) {
67 1
            return $this->resolveVariadicOrBuiltinOrNonTyped();
68
        }
69
70 48
        if ($this->isUnionType()) {
71 9
            return $this->resolveUnionType($container);
72
        }
73
74 39
        if (!$this->isBuiltin()) {
75
            /** @var ReflectionNamedType $type */
76 19
            $typeName = $type->getName();
77 19
            if ($typeName === 'self') {
78
                // If type name is "self", it means that called class and
79
                // $parameter->getDeclaringClass() returned instance of `ReflectionClass`.
80
                /** @psalm-suppress PossiblyNullReference */
81 1
                $typeName = $this->parameter->getDeclaringClass()->getName();
82
            }
83
84
            try {
85
                /** @var mixed */
86 19
                $result = $container->get($typeName);
87 13
            } catch (Throwable $t) {
88
                if (
89 13
                    $this->parameter->isOptional()
90
                    && (
91 7
                        $t instanceof CircularReferenceException
92 13
                        || !$container->has($typeName)
93
                    )
94
                ) {
95 6
                    return $this->parameter->getDefaultValue();
96
                }
97 7
                throw $t;
98
            }
99
100 6
            if (!$result instanceof $typeName) {
101 1
                $actualType = $this->getValueType($result);
102 1
                throw new InvalidConfigException(
103 1
                    "Container returned incorrect type \"$actualType\" for service \"{$type->getName()}\"."
104
                );
105
            }
106 5
            return $result;
107
        }
108
109 22
        return $this->resolveVariadicOrBuiltinOrNonTyped();
110
    }
111
112
    /**
113
     * @return mixed
114
     */
115 24
    private function resolveVariadicOrBuiltinOrNonTyped()
116
    {
117 24
        if ($this->parameter->isDefaultValueAvailable()) {
118 21
            return $this->parameter->getDefaultValue();
119
        }
120
121 3
        if ($this->isOptional()) {
122
            throw new NotInstantiableException(
123
                sprintf(
124
                    'Can not determine default value of parameter "%s" when instantiating "%s" ' .
125
                    'because it is PHP internal. Please specify argument explicitly.',
126
                    $this->parameter->getName(),
127
                    $this->getCallable(),
128
                )
129
            );
130
        }
131
132 3
        $type = $this->getType();
133
134 3
        if ($type === null) {
135 1
            throw new NotInstantiableException(
136 1
                sprintf(
137
                    'Can not determine value of the "%s" parameter without type when instantiating "%s". ' .
138
                    'Please specify argument explicitly.',
139 1
                    $this->parameter->getName(),
140 1
                    $this->getCallable(),
141
                )
142
            );
143
        }
144
145 2
        throw new NotInstantiableException(
146 2
            sprintf(
147 2
                'Can not determine value of the "%s" parameter of type "%s" when instantiating "%s". ' .
148
                'Please specify argument explicitly.',
149 2
                $this->parameter->getName(),
150
                $type,
151 2
                $this->getCallable(),
152
            )
153
        );
154
    }
155
156
    /**
157
     * Resolve union type string provided as a class name.
158
     *
159
     * @throws InvalidConfigException If an object of incorrect type was created.
160
     * @throws Throwable
161
     *
162
     * @return mixed|null Ready to use object or null if definition can
163
     * not be resolved and is marked as optional.
164
     */
165 9
    private function resolveUnionType(ContainerInterface $container)
166
    {
167
        /**
168
         * @psalm-suppress UndefinedClass
169
         *
170
         * @var ReflectionUnionType $parameterType
171
         */
172 9
        $parameterType = $this->parameter->getType();
173
        /**
174
         * @var \ReflectionType[] $types
175
         * @psalm-suppress UndefinedClass
176
         */
177 9
        $types = $parameterType->getTypes();
178 9
        $class = implode('|', $types);
179
180 9
        foreach ($types as $type) {
181 9
            if (!$type->isBuiltin()) {
182
                /** @var ReflectionNamedType $type */
183 8
                $typeName = $type->getName();
184 8
                if ($typeName === 'self') {
185
                    // If type name is "self", it means that called class and
186
                    // $parameter->getDeclaringClass() returned instance of `ReflectionClass`.
187
                    /** @psalm-suppress PossiblyNullReference */
188 1
                    $typeName = $this->parameter->getDeclaringClass()->getName();
189
                }
190
191
                try {
192
                    /** @var mixed */
193 8
                    $result = $container->get($typeName);
194 3
                    $resolved = true;
195 7
                } catch (Throwable $t) {
196 7
                    $error = $t;
197 7
                    $resolved = false;
198
                }
199
200 8
                if ($resolved) {
201
                    /** @var mixed $result Exist, because $resolved is true */
202 3
                    if (!$result instanceof $typeName) {
203 1
                        $actualType = $this->getValueType($result);
204 1
                        throw new InvalidConfigException(
205 1
                            "Container returned incorrect type \"$actualType\" for service \"$class\"."
206
                        );
207
                    }
208 2
                    return $result;
209
                }
210
211
                /** @var Throwable $error Exist, because $resolved is false */
212
                if (
213 7
                    !$error instanceof CircularReferenceException
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $error does not seem to be defined for all execution paths leading up to this point.
Loading history...
214 7
                    && $container->has($typeName)
215
                ) {
216 1
                    throw $error;
217
                }
218
            }
219
        }
220
221 5
        if ($this->parameter->isOptional()) {
222 2
            return null;
223
        }
224
225 3
        if (!isset($error)) {
226 1
            return $this->resolveVariadicOrBuiltinOrNonTyped();
227
        }
228
229 2
        throw $error;
230
    }
231
232 48
    private function isUnionType(): bool
233
    {
234
        /** @psalm-suppress UndefinedClass */
235 48
        return $this->parameter->getType() instanceof ReflectionUnionType;
236
    }
237
238 3
    private function getType(): ?string
239
    {
240 3
        $type = $this->parameter->getType();
241
242
        /** @psalm-suppress UndefinedClass, TypeDoesNotContainType */
243 3
        if ($type instanceof ReflectionUnionType) {
244
            /** @var ReflectionNamedType[] */
245 1
            $namedTypes = $type->getTypes();
246 1
            $names = array_map(
247 1
                static fn (ReflectionNamedType $t) => $t->getName(),
248
                $namedTypes
249
            );
250 1
            return implode('|', $names);
251
        }
252
253 2
        if ($type instanceof ReflectionNamedType) {
254 1
            return $type->getName();
255
        }
256
257 1
        return null;
258
    }
259
260 3
    private function getCallable(): string
261
    {
262 3
        $callable = [];
263
264 3
        $class = $this->parameter->getDeclaringClass();
265 3
        if ($class !== null) {
266 3
            $callable[] = $class->getName();
267
        }
268 3
        $callable[] = $this->parameter->getDeclaringFunction()->getName() . '()';
269
270 3
        return implode('::', $callable);
271
    }
272
273
    /**
274
     * Get type of the value provided.
275
     *
276
     * @param mixed $value Value to get type for.
277
     */
278 2
    private function getValueType($value): string
279
    {
280 2
        return is_object($value) ? get_class($value) : gettype($value);
281
    }
282
}
283