Passed
Pull Request — master (#37)
by Sergei
02:47
created

ParameterDefinition   A

Complexity

Total Complexity 40

Size/Duplication

Total Lines 260
Duplicated Lines 0 %

Test Coverage

Coverage 96.33%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 111
c 2
b 0
f 0
dl 0
loc 260
ccs 105
cts 109
cp 0.9633
rs 9.2
wmc 40

12 Methods

Rating   Name   Duplication   Size   Complexity  
A hasValue() 0 3 1
A isVariadic() 0 3 1
A isOptional() 0 3 1
A __construct() 0 3 1
A getReflection() 0 3 1
A getType() 0 20 3
A isUnionType() 0 4 1
A getCallable() 0 14 2
A getValueType() 0 3 2
B resolveUnionType() 0 68 11
C resolve() 0 54 12
A resolveVariadicOrBuiltinOrNonTyped() 0 37 4

How to fix   Complexity   

Complex Class

Complex classes like ParameterDefinition often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ParameterDefinition, and based on these observations, apply Extract Interface, too.

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 52
    public function __construct(ReflectionParameter $parameter)
29
    {
30 52
        $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 20
    public function hasValue(): bool
49
    {
50 20
        return $this->parameter->isDefaultValueAvailable();
51
    }
52
53 49
    public function resolve(ContainerInterface $container)
54
    {
55 49
        $type = $this->parameter->getType();
56
57 49
        if ($type === null || $this->isVariadic()) {
58 1
            return $this->resolveVariadicOrBuiltinOrNonTyped();
59
        }
60
61 48
        if ($this->isUnionType()) {
62 9
            return $this->resolveUnionType($container);
63
        }
64
65
        /** @var ReflectionNamedType|null $type */
66 39
        $type = $this->parameter->getType();
67 39
        $isBuiltin = $type !== null && $type->isBuiltin();
68
69 39
        if (!$isBuiltin) {
70
            /** @var ReflectionNamedType $type */
71 19
            $typeName = $type->getName();
72 19
            if ($typeName === 'self') {
73
                // If type name is "self", it means that called class and
74
                // $parameter->getDeclaringClass() returned instance of `ReflectionClass`.
75
                /** @psalm-suppress PossiblyNullReference */
76 1
                $typeName = $this->parameter
77 1
                    ->getDeclaringClass()
78 1
                    ->getName();
79
            }
80
81
            try {
82
                /** @var mixed */
83 19
                $result = $container->get($typeName);
84 13
            } catch (Throwable $t) {
85
                if (
86 13
                    $this->parameter->isOptional()
87
                    && (
88 7
                        $t instanceof CircularReferenceException
89 13
                        || !$container->has($typeName)
90
                    )
91
                ) {
92 6
                    return $this->parameter->getDefaultValue();
93
                }
94 7
                throw $t;
95
            }
96
97 6
            if (!$result instanceof $typeName) {
98 1
                $actualType = $this->getValueType($result);
99 1
                throw new InvalidConfigException(
100 1
                    "Container returned incorrect type \"$actualType\" for service \"{$type->getName()}\"."
101
                );
102
            }
103 5
            return $result;
104
        }
105
106 22
        return $this->resolveVariadicOrBuiltinOrNonTyped();
107
    }
108
109
    /**
110
     * @return mixed
111
     */
112 24
    private function resolveVariadicOrBuiltinOrNonTyped()
113
    {
114 24
        if ($this->parameter->isDefaultValueAvailable()) {
115 21
            return $this->parameter->getDefaultValue();
116
        }
117
118 3
        if ($this->isOptional()) {
119
            throw new NotInstantiableException(
120
                sprintf(
121
                    'Can not determine default value of parameter "%s" when instantiating "%s" ' .
122
                    'because it is PHP internal. Please specify argument explicitly.',
123
                    $this->parameter->getName(),
124
                    $this->getCallable(),
125
                )
126
            );
127
        }
128
129 3
        $type = $this->getType();
130
131 3
        if ($type === null) {
132 1
            throw new NotInstantiableException(
133 1
                sprintf(
134
                    'Can not determine value of the "%s" parameter without type when instantiating "%s". ' .
135
                    'Please specify argument explicitly.',
136 1
                    $this->parameter->getName(),
137 1
                    $this->getCallable(),
138
                )
139
            );
140
        }
141
142 2
        throw new NotInstantiableException(
143 2
            sprintf(
144 2
                'Can not determine value of the "%s" parameter of type "%s" when instantiating "%s". ' .
145
                'Please specify argument explicitly.',
146 2
                $this->parameter->getName(),
147
                $type,
148 2
                $this->getCallable(),
149
            )
150
        );
151
    }
152
153
    /**
154
     * Resolve union type string provided as a class name.
155
     *
156
     * @throws InvalidConfigException If an object of incorrect type was created.
157
     * @throws Throwable
158
     *
159
     * @return mixed|null Ready to use object or null if definition can
160
     * not be resolved and is marked as optional.
161
     */
162 9
    private function resolveUnionType(ContainerInterface $container)
163
    {
164
        /**
165
         * @var ReflectionUnionType $parameterType
166
         */
167 9
        $parameterType = $this->parameter->getType();
168
169
        /**
170
         * @var ReflectionNamedType[] $types
171
         */
172 9
        $types = $parameterType->getTypes();
173 9
        $class = implode('|', $types);
174
175 9
        foreach ($types as $type) {
176 9
            if (!$type->isBuiltin()) {
177 8
                $typeName = $type->getName();
178
                /**
179
                 * @psalm-suppress TypeDoesNotContainType
180
                 * @link https://github.com/vimeo/psalm/issues/6756
181
                 */
182 8
                if ($typeName === 'self') {
183
                    // If type name is "self", it means that called class and
184
                    // $parameter->getDeclaringClass() returned instance of `ReflectionClass`.
185
                    /** @psalm-suppress PossiblyNullReference */
186 1
                    $typeName = $this->parameter
187 1
                        ->getDeclaringClass()
188 1
                        ->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
269 3
                ->getDeclaringFunction()
270 3
                ->getName() .
271
            '()';
272
273 3
        return implode('::', $callable);
274
    }
275
276
    /**
277
     * Get type of the value provided.
278
     *
279
     * @param mixed $value Value to get type for.
280
     */
281 2
    private function getValueType($value): string
282
    {
283 2
        return is_object($value) ? get_class($value) : gettype($value);
284
    }
285
}
286