Test Failed
Pull Request — master (#37)
by Divine Niiquaye
02:41
created

Resolver::autowireService()   F

Complexity

Conditions 35
Paths 296

Size

Total Lines 75
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 35
eloc 46
nc 296
nop 3
dl 0
loc 75
rs 2.1333
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of DivineNii opensource projects.
7
 *
8
 * PHP version 7.4 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2021 DivineNii (https://divinenii.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
18
namespace Rade\DI;
19
20
use Nette\Utils\{Callback, Reflection};
21
use PhpParser\BuilderFactory;
22
use PhpParser\Node\{Expr, Stmt, Scalar};
23
use Rade\DI\Exceptions\{ContainerResolutionException, NotFoundServiceException};
24
use Symfony\Contracts\Service\{ServiceProviderInterface, ServiceSubscriberInterface};
25
26
/**
27
 * Class Resolver.
28
 *
29
 * @author Divine Niiquaye Ibok <[email protected]>
30
 */
31
class Resolver
32
{
33
    private AbstractContainer $container;
34
35
    private ?BuilderFactory $builder;
36
37
    private bool $strict = true;
38
39
    /** @var array<string,\PhpParser\Node> */
40
    private array $literalCache = [];
41
42
    public function __construct(AbstractContainer $container, BuilderFactory $builder = null)
43
    {
44
        $this->builder = $builder;
45
        $this->container = $container;
46
    }
47
48
    /**
49
     * If true, exception will be thrown on resolvable services with are not typed.
50
     */
51
    public function setStrictAutowiring(bool $boolean = true): void
52
    {
53
        $this->strict = $boolean;
54
    }
55
56
    /**
57
     * The method name generated for a service definition.
58
     */
59
    public function createMethod(string $id): string
60
    {
61
        return 'get' . \str_replace(['.', '_', '\\'], '', \ucwords($id, '._'));
62
    }
63
64
    /**
65
     * @param mixed $definition
66
     */
67
    public static function autowireService($definition, bool $allTypes = false, AbstractContainer $container = null): array
68
    {
69
        $types = $autowired = [];
70
71
        if (\is_callable($definition)) {
72
            $definition = \Closure::fromCallable($definition);
73
        }
74
75
        if ($definition instanceof \Closure) {
76
            $definition = Callback::unwrap($definition);
77
            $types = self::getTypes(\is_array($definition) ? new \ReflectionMethod($definition[0], $definition[1]) : new \ReflectionFunction($definition));
0 ignored issues
show
introduced by
The condition is_array($definition) is always true.
Loading history...
78
        } elseif (\is_string($definition)) {
79
            if (!(\class_exists($definition) || \interface_exists($definition))) {
80
                return $allTypes ? ['string'] : [];
81
            }
82
83
            $types[] = $definition;
84
        } elseif (\is_array($definition)) {
85
            if (null !== $container && 2 === \count($definition, \COUNT_RECURSIVE)) {
86
                if ($definition[0] instanceof Definitions\Reference) {
87
                    $def = $container->definition((string) $definition[0]);
88
                } elseif ($definition[0] instanceof Expr\BinaryOp\Coalesce) {
89
                    $def = $container->definition($definition[0]->left->dim->value);
90
                }
91
92
                if (isset($def)) {
93
                    $types = self::getTypes(new \ReflectionMethod($def instanceof Definitions\DefinitionInterface ? $def->getEntity() : $def, $definition[1]));
94
95
                    goto resolve_types;
96
                }
97
            }
98
99
            return $allTypes ? ['array'] : [];
100
        }
101
102
        if (\is_callable($definition)) {
103
            $types = self::getTypes(Callback::toReflection($definition));
104
        } elseif (\is_string($definition)) {
105
            if (!(\class_exists($definition) || \interface_exists($definition))) {
106
                return $allTypes ? ['string'] : $types;
107
            }
108
109
            $types[] = $definition;
110
        } elseif (\is_object($definition)) {
111
            if ($definition instanceof \stdClass) {
112
                return $allTypes ? ['object'] : $types;
113
            }
114
115
            $types[] = \get_class($definition);
116
        } elseif (\is_array($definition)) {
117
            if (null !== $container && 2 === \count($definition, \COUNT_RECURSIVE)) {
118
                if ($definition[0] instanceof Definitions\Reference) {
119
                    $types = self::getTypes(new \ReflectionMethod($container->definition((string) $definition[0])->getEntity(), $definition[1]));
120
                } elseif ($definition[0] instanceof Expr\BinaryOp\Coalesce) {
121
                    $types = self::getTypes(new \ReflectionMethod($container->definition($definition[0]->left->dim->value)->getEntity(), $definition[1]));
122
                }
123
            } else {
124
                return $allTypes ? ['array'] : [];
125
            }
126
        }
127
128
        resolve_types:
129
        foreach (($types ?? []) as $type) {
130
            $autowired[] = $type;
131
132
            foreach (\class_implements($type) ?: [] as $interface) {
133
                $autowired[] = $interface;
134
            }
135
136
            foreach (\class_parents($type) ?: [] as $parent) {
137
                $autowired[] = $parent;
138
            }
139
        }
140
141
        return $autowired;
142
    }
143
144
    /**
145
     * Resolves arguments for callable.
146
     *
147
     * @param array<int|string,mixed> $args
148
     *
149
     * @return array<int,mixed>
150
     */
151
    public function autowireArguments(\ReflectionFunctionAbstract $function, array $args = []): array
152
    {
153
        $resolvedParameters = [];
154
        $nullValuesFound = 0;
155
        $args = $this->resolveArguments($args); // Resolves provided arguments.
156
157
        foreach ($function->getParameters() as $offset => $parameter) {
158
            $position = 0 === $nullValuesFound ? $offset : $parameter->name;
159
            $resolved = $args[$offset] ?? $args[$parameter->name] ?? null;
160
            $types = self::getTypes($parameter);
161
162
            if (\PHP_VERSION_ID >= 80100 && (\count($types) > 1 && \is_subclass_of($enumType = $types[0], \BackedEnum::class))) {
0 ignored issues
show
Bug introduced by
The type BackedEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
163
                if (null === ($resolved = $resolved ?? $providedParameters[$enumType] ?? null)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $providedParameters seems to never exist and therefore isset should always be false.
Loading history...
164
                    throw new ContainerResolutionException(\sprintf('Missing parameter %s.', Reflection::toString($parameter)));
165
                }
166
                $resolvedParameters[$position] = $enumType::from($resolved);
167
168
                continue;
169
            }
170
171
            if (null === ($resolved = $resolved ?? $this->autowireArgument($parameter, $types, $args))) {
172
                if ($parameter->isDefaultValueAvailable()) {
173
                    if (\PHP_MAJOR_VERSION < 8) {
174
                        $resolvedParameters[$position] = Reflection::getParameterDefaultValue($parameter);
175
                    } else {
176
                        ++$nullValuesFound;
177
                    }
178
                } elseif (!$parameter->isVariadic()) {
179
                    $resolvedParameters[$position] = self::getParameterDefaultValue($parameter, $types);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $resolvedParameters[$position] is correct as self::getParameterDefaultValue($parameter, $types) targeting Rade\DI\Resolver::getParameterDefaultValue() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
180
                }
181
182
                continue;
183
            }
184
185
            if ($parameter->isVariadic() && \is_array($resolved)) {
186
                $resolvedParameters = \array_merge($resolvedParameters, $resolved);
187
188
                continue;
189
            }
190
191
            $resolvedParameters[$position] = $resolved;
192
        }
193
194
        return $resolvedParameters;
195
    }
196
197
    /**
198
     * Resolve a service definition, class string, invocable object or callable
199
     * using autowiring.
200
     *
201
     * @param string|callable|object  $callback
202
     * @param array<int|string,mixed> $args
203
     *
204
     * @throws ContainerResolutionException|\ReflectionException if unresolvable
205
     *
206
     * @return mixed
207
     */
208
    public function resolve($callback, array $args = [])
209
    {
210
        if ($callback instanceof Definitions\Statement) {
211
            if (Services\ServiceLocator::class == ($value = $callback->getValue())) {
212
                $services = [];
213
214
                foreach (($callback->getArguments() ?: $args) as $name => $service) {
215
                    $services += $this->resolveServiceSubscriber($name, (string) $service);
216
                }
217
218
                $resolved = null === $this->builder ? new Services\ServiceLocator($services) : $this->builder->new('\\' . Services\ServiceLocator::class, [$services]);
219
            } else {
220
                $resolved = $this->resolve($value, $callback->getArguments() ?: $args);
221
222
                if ($callback->isClosureWrappable()) {
223
                    $resolved = null === $this->builder ? fn () => $resolved : new Expr\ArrowFunction(['expr' => $resolved]);
224
                }
225
            }
226
        } elseif ($callback instanceof Definitions\Reference) {
227
            $resolved = $this->resolveReference((string) $callback);
228
229
            if (\is_callable($resolved) || (\is_array($resolved) && 2 === \count($resolved, \COUNT_RECURSIVE))) {
230
                $resolved = $this->resolveCallable($resolved, $args);
231
            } else {
232
                $callback = $resolved;
233
            }
234
        } elseif ($callback instanceof Definitions\ValueDefinition) {
235
            $resolved = $callback->getEntity();
236
        } elseif ($callback instanceof Definitions\TaggedLocator) {
237
            $resolved = $this->resolve($callback->resolve($this->container));
238
        } elseif ($callback instanceof Builder\PhpLiteral) {
239
            $expression = $this->literalCache[\spl_object_id($callback)] ??= $callback->resolve($this)[0];
240
            $resolved = $expression instanceof Stmt\Expression ? $expression->expr : $expression;
241
        } elseif (\is_string($callback)) {
242
            if (\str_contains($callback, '%')) {
243
                $callback = $this->container->parameter($callback);
244
            }
245
246
            if (\class_exists($callback)) {
247
                return $this->resolveClass($callback, $args);
248
            }
249
250
            if (\is_callable($callback)) {
251
                $resolved = $this->resolveCallable($callback, $args);
252
            }
253
        } elseif (\is_callable($callback) || \is_array($callback)) {
254
            $resolved = $this->resolveCallable($callback, $args);
0 ignored issues
show
Bug introduced by
It seems like $callback can also be of type object; however, parameter $callback of Rade\DI\Resolver::resolveCallable() does only seem to accept array<integer,mixed>|callable, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

254
            $resolved = $this->resolveCallable(/** @scrutinizer ignore-type */ $callback, $args);
Loading history...
255
        }
256
257
        return $resolved ?? (null === $this->builder ? $callback : $this->builder->val($callback));
258
    }
259
260
    /**
261
     * Resolves callables and array like callables.
262
     *
263
     * @param callable|array<int,mixed> $callback
264
     * @param array<int|string,mixed>   $arguments
265
     *
266
     * @throws \ReflectionException if $callback is not a real callable
267
     *
268
     * @return mixed
269
     */
270
    public function resolveCallable($callback, array $arguments = [])
271
    {
272
        if (\is_array($callback)) {
273
            if (2 === \count($callback, \COUNT_RECURSIVE)) {
274
                $callback[0] = $this->resolve($callback[0]);
275
276
                if ($callback[0] instanceof Expr\BinaryOp\Coalesce) {
277
                    $type = [$this->container->definition($callback[0]->left->dim->value)->getEntity(), $callback[1]];
278
                } elseif ($callback[0] instanceof Expr\New_) {
279
                    $type = [(string) $callback[0]->class, $callback[1]];
280
                }
281
282
                if (isset($type) || \is_callable($callback)) {
283
                    goto create_callable;
284
                }
285
            }
286
287
            $callback = $this->resolveArguments($callback);
0 ignored issues
show
Bug introduced by
It seems like $callback can also be of type callable; however, parameter $arguments of Rade\DI\Resolver::resolveArguments() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

287
            $callback = $this->resolveArguments(/** @scrutinizer ignore-type */ $callback);
Loading history...
288
289
            return null === $this->builder ? $callback : $this->builder->val($callback);
290
        }
291
292
        create_callable:
293
        $args = $this->autowireArguments($ref = Callback::toReflection($type ?? $callback), $arguments);
294
295
        if ($ref instanceof \ReflectionFunction) {
296
            return null === $this->builder ? $ref->invokeArgs($args) : $this->builder->funcCall($callback, $args);
0 ignored issues
show
Bug introduced by
$callback of type array<integer,mixed>|callable is incompatible with the type PhpParser\Node\Expr|PhpParser\Node\Name|string expected by parameter $name of PhpParser\BuilderFactory::funcCall(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

296
            return null === $this->builder ? $ref->invokeArgs($args) : $this->builder->funcCall(/** @scrutinizer ignore-type */ $callback, $args);
Loading history...
297
        }
298
299
        if ($ref->isStatic()) {
300
            $className = \is_array($callback) ? $callback[0] : $ref->getDeclaringClass()->getName();
301
302
            return null === $this->builder ? $ref->invokeArgs(null, $args) : $this->builder->staticCall($className, $ref->getName(), $args);
303
        }
304
305
        return null === $this->builder ? $callback(...$args) : $this->builder->methodCall($callback[0], $ref->getName(), $args);
306
    }
307
308
    /**
309
     * @param array<int|string,mixed> $args
310
     *
311
     * @throws ContainerResolutionException|\ReflectionException if class string unresolvable
312
     */
313
    public function resolveClass(string $class, array $args = []): object
314
    {
315
        /** @var class-string $class */
316
        $reflection = new \ReflectionClass($class);
317
318
        if ($reflection->isAbstract() || !$reflection->isInstantiable()) {
319
            throw new ContainerResolutionException(\sprintf('Class %s is an abstract type or instantiable.', $class));
320
        }
321
322
        if (null === $constructor = $reflection->getConstructor()) {
323
            if (!empty($args)) {
324
                throw new ContainerResolutionException(\sprintf('Unable to pass arguments, class "%s" has no constructor.', $class));
325
            }
326
327
            $service = null === $this->builder ? $reflection->newInstanceWithoutConstructor() : $this->builder->new($class);
328
        } else {
329
            $args = $this->autowireArguments($constructor, $args);
330
            $service = null === $this->builder ? $reflection->newInstanceArgs($args) : $this->builder->new($class, $args);
331
        }
332
333
        if ($reflection->implementsInterface(Injector\InjectableInterface::class)) {
334
            return Injector\Injectable::getProperties($this, $service, $reflection);
335
        }
336
337
        return $service;
338
    }
339
340
    /**
341
     * @param array<int|string,mixed> $arguments
342
     *
343
     * @return array<int|string,mixed>
344
     */
345
    public function resolveArguments(array $arguments = []): array
346
    {
347
        foreach ($arguments as $key => $value) {
348
            if ($value instanceof \stdClass) {
349
                $resolved = null === $this->builder ? $value : new Expr\Cast\Object_($this->builder->val($this->resolveArguments((array) $value)));
350
            } elseif (\is_array($value)) {
351
                $resolved = $this->resolveArguments($value);
352
            } elseif (\is_int($value)) {
353
                $resolved = null === $this->builder ? $value : new Scalar\LNumber($value);
354
            } elseif (\is_float($value)) {
355
                $resolved = null === $this->builder ? (int) $value : new Scalar\DNumber($value);
356
            } elseif (\is_numeric($value)) {
357
                $resolved = null === $this->builder ? (int) $value : Scalar\LNumber::fromString($value);
358
            } elseif (\is_string($value)) {
359
                if (\str_contains($value, '%')) {
360
                    $value = $this->container->parameter($value);
361
                }
362
363
                $resolved = null === $this->builder ? $value : $this->builder->val($value);
364
            } else {
365
                $resolved = $this->resolve($value);
366
            }
367
368
            $arguments[$key] = $resolved;
369
        }
370
371
        return $arguments;
372
    }
373
374
    /**
375
     * Resolves service by type.
376
     *
377
     * @param string $id A class or an interface name
378
     *
379
     * @return mixed
380
     */
381
    public function get(string $id, bool $single = false)
382
    {
383
        if (\is_subclass_of($id, ServiceSubscriberInterface::class)) {
384
            static $services = [];
385
386
            foreach ($id::getSubscribedServices() as $name => $service) {
387
                $services += $this->resolveServiceSubscriber($name, $service);
388
            }
389
390
            if (null === $builder = $this->builder) {
391
                return new Services\ServiceLocator($services);
392
            }
393
394
            return $builder->new('\\' . Services\ServiceLocator::class, [$services]);
395
        }
396
397
        if (!$this->strict) {
398
            return $this->container->get($id, $single ? $this->container::EXCEPTION_ON_MULTIPLE_SERVICE : $this->container::IGNORE_MULTIPLE_SERVICE);
399
        }
400
401
        if ($this->container->typed($id)) {
402
            return $this->container->autowired($id, $single);
403
        }
404
405
        throw new NotFoundServiceException(\sprintf('Service of type "%s" not found. Check class name because it cannot be found.', $id));
406
    }
407
408
    /**
409
     * Gets the PHP's parser builder.
410
     */
411
    public function getBuilder(): ?BuilderFactory
412
    {
413
        return $this->builder;
414
    }
415
416
    /**
417
     * @return mixed
418
     */
419
    private function resolveReference(string $reference)
420
    {
421
        if ('?' === $reference[0]) {
422
            $invalidBehavior = $this->container::EXCEPTION_ON_MULTIPLE_SERVICE;
423
            $reference = \substr($reference, 1);
424
425
            if ($arrayLike = \str_ends_with('[]', $reference)) {
426
                $reference = \substr($reference, 0, -2);
427
                $invalidBehavior = $this->container::IGNORE_MULTIPLE_SERVICE;
428
            }
429
430
            if ($this->container->has($reference) || $this->container->typed($reference)) {
431
                return $this->container->get($reference, $invalidBehavior);
432
            }
433
434
            return $arrayLike ? [] : null;
435
        }
436
437
        if ('[]' === \substr($reference, -2)) {
438
            return $this->container->get(\substr($reference, 0, -2), $this->container::IGNORE_MULTIPLE_SERVICE);
439
        }
440
441
        return $this->container->get($reference);
442
    }
443
444
    /**
445
     * Resolves services for ServiceLocator.
446
     *
447
     * @param int|string $id
448
     *
449
     * @return (\Closure|array|mixed|null)[]
450
     */
451
    private function resolveServiceSubscriber($id, string $value): array
452
    {
453
        if ('?' === $value[0]) {
454
            $arrayLike = \str_ends_with($value = \substr($value, 1), '[]');
455
456
            if (\is_int($id)) {
457
                $id = $arrayLike ? \substr($value, 0, -2) : $value;
458
            }
459
460
            return ($this->container->has($id) || $this->container->typed($id)) ? $this->resolveServiceSubscriber($id, $value) : [$id => $arrayLike ? [] : null];
461
        }
462
463
        $service = function () use ($value) {
464
            if ('[]' === \substr($value, -2)) {
465
                $service = $this->container->get(\substr($value, 0, -2), $this->container::IGNORE_MULTIPLE_SERVICE);
466
467
                return \is_array($service) ? $service : [$service];
468
            }
469
470
            return $this->container->get($value);
471
        };
472
473
        if (null !== $this->builder) {
474
            if ($this->container->has($value)) {
475
                $returnType = $this->container->definition($value)->getTypes()[0] ?? (\class_exists($id) || \interface_exists($id) ? $id : null);
476
            } elseif ('[]' !== \substr($value, -2)) {
477
                $returnType = 'array';
478
            }
479
480
            $service = new Expr\ArrowFunction(['expr' => $this->builder->val($service()), 'returnType' => $returnType ?? null]);
481
        }
482
483
        return [\is_int($id) ? \rtrim($value, '[]') : $id => $service];
484
    }
485
486
    /**
487
     * Resolves missing argument using autowiring.
488
     *
489
     * @param array<int|string,mixed> $providedParameters
490
     * @param array<int,string>       $types
491
     *
492
     * @throws ContainerResolutionException
493
     *
494
     * @return mixed
495
     */
496
    private function autowireArgument(\ReflectionParameter $parameter, array $types, array $providedParameters)
497
    {
498
        foreach ($types as $typeName) {
499
            if (!Reflection::isBuiltinType($typeName)) {
500
                try {
501
                    return $providedParameters[$typeName] ?? $this->get($typeName, !$parameter->isVariadic());
502
                } catch (NotFoundServiceException $e) {
503
                    // Ignore this exception ...
504
                } catch (ContainerResolutionException $e) {
505
                    $errorException = new ContainerResolutionException(\sprintf("{$e->getMessage()} (needed by %s)", Reflection::toString($parameter)));
506
                }
507
508
                if (
509
                    ServiceProviderInterface::class === $typeName &&
510
                    null !== $class = $parameter->getDeclaringClass()
511
                ) {
512
                    if (!$class->implementsInterface(ServiceSubscriberInterface::class)) {
513
                        throw new ContainerResolutionException(\sprintf(
514
                            'Service of type %s needs parent class %s to implement %s.',
515
                            $typeName,
516
                            $class->getName(),
517
                            ServiceSubscriberInterface::class
518
                        ));
519
                    }
520
521
                    return $this->get($class->getName());
522
                }
523
            }
524
525
            if (\PHP_MAJOR_VERSION >= 8 && $attributes = $parameter->getAttributes()) {
526
                foreach ($attributes as $attribute) {
527
                    if (Attribute\Inject::class === $attribute->getName()) {
528
                        if (null === $attrName = $attribute->getArguments()[0] ?? null) {
529
                            throw new ContainerResolutionException(\sprintf('Using the Inject attribute on parameter %s requires a value to be set.', $parameter->getName()));
530
                        }
531
532
                        if ($arrayLike = \str_ends_with($attrName, '[]')) {
533
                            $attrName = \substr($attrName, 0, -2);
534
                        }
535
536
                        try {
537
                            return $this->get($attrName, !$arrayLike);
538
                        } catch (NotFoundServiceException $e) {
539
                            // Ignore this exception ...
540
                        }
541
                    }
542
                }
543
            }
544
545
            if (
546
                ($method = $parameter->getDeclaringFunction()) instanceof \ReflectionMethod
547
                && \preg_match('#@param[ \t]+([\w\\\\]+)(?:\[\])?[ \t]+\$' . $parameter->name . '#', (string) $method->getDocComment(), $m)
548
                && ($itemType = Reflection::expandClassName($m[1], $method->getDeclaringClass()))
549
                && (\class_exists($itemType) || \interface_exists($itemType))
550
            ) {
551
                try {
552
                    if (\in_array($typeName, ['array', 'iterable'], true)) {
553
                        return $this->get($itemType);
554
                    }
555
556
                    if ('object' === $typeName || \is_subclass_of($itemType, $typeName)) {
557
                        return $this->get($itemType, true);
558
                    }
559
                } catch (NotFoundServiceException $e) {
560
                    // Ignore this exception ...
561
                }
562
            }
563
564
            if (isset($errorException)) {
565
                throw $errorException;
566
            }
567
        }
568
569
        return null;
570
    }
571
572
    /**
573
     * Returns an associated type to the given parameter if available.
574
     *
575
     * @param \ReflectionParameter|\ReflectionFunctionAbstract $reflection
576
     *
577
     * @return array<int,string>
578
     */
579
    private static function getTypes(\Reflector $reflection): array
580
    {
581
        if ($reflection instanceof \ReflectionParameter) {
582
            $type = $reflection->getType();
583
        } elseif ($reflection instanceof \ReflectionFunctionAbstract) {
584
            $type = $reflection->getReturnType() ?? (PHP_VERSION_ID >= 80100 ? $reflection->getTentativeReturnType() : null);
0 ignored issues
show
Bug introduced by
The method getTentativeReturnType() does not exist on ReflectionFunctionAbstract. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

584
            $type = $reflection->getReturnType() ?? (PHP_VERSION_ID >= 80100 ? $reflection->/** @scrutinizer ignore-call */ getTentativeReturnType() : null);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
585
        }
586
587
        if (!isset($type)) {
588
            return [];
589
        }
590
591
        $resolver = static function (\ReflectionNamedType $rName) use ($reflection): string {
592
            $function = $reflection instanceof \ReflectionParameter ? $reflection->getDeclaringFunction() : $reflection;
593
594
            if ($function instanceof \ReflectionMethod) {
595
                $lcName = \strtolower($rName->getName());
596
597
                if ('self' === $lcName || 'static' === $lcName) {
598
                    return $function->getDeclaringClass()->name;
599
                }
600
601
                if ('parent' === $lcName) {
602
                    return $function->getDeclaringClass()->getParentClass()->name;
603
                }
604
            }
605
606
            return $rName->getName();
607
        };
608
609
        if (!$type instanceof \ReflectionNamedType) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $type does not seem to be defined for all execution paths leading up to this point.
Loading history...
610
            return \array_map($resolver, $type->getTypes());
611
        }
612
613
        return [$resolver($type)];
614
    }
615
616
    /**
617
     * Get the parameter's allowed null else error.
618
     *
619
     * @throws \ReflectionException|ContainerResolutionException
620
     *
621
     * @return null
622
     */
623
    private static function getParameterDefaultValue(\ReflectionParameter $parameter, array $types)
624
    {
625
        if ($parameter->isOptional() || $parameter->allowsNull()) {
626
            return null;
627
        }
628
629
        $errorDescription = 'Parameter ' . Reflection::toString($parameter);
630
631
        if ('' === ($typedHint = \implode('|', $types))) {
632
            $errorDescription .= ' has no type hint or default value.';
633
        } elseif (\str_contains($typedHint, '|')) {
634
            $errorDescription .= ' has multiple type-hints ("' . $typedHint . '").';
635
        } elseif (\class_exists($typedHint)) {
636
            $errorDescription .= ' has an unresolved class-based type-hint ("' . $typedHint . '").';
637
        } elseif (\interface_exists($typedHint)) {
638
            $errorDescription .= ' has an unresolved interface-based type-hint ("' . $typedHint . '").';
639
        } else {
640
            $errorDescription .= ' has a type-hint ("' . $typedHint  . '") that cannot be resolved, perhaps a you forgot to set it up?';
641
        }
642
643
        throw new ContainerResolutionException($errorDescription);
644
    }
645
}
646