Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace DI\Invoker;
6
 
7
use Invoker\ParameterResolver\ParameterResolver;
8
use Psr\Container\ContainerInterface;
9
use ReflectionFunctionAbstract;
10
use ReflectionNamedType;
11
 
12
/**
13
 * Inject the container, the definition or any other service using type-hints.
14
 *
15
 * {@internal This class is similar to TypeHintingResolver and TypeHintingContainerResolver,
16
 *            we use this instead for performance reasons}
17
 *
18
 * @author Quim Calpe <quim@kalpe.com>
19
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
20
 */
21
class FactoryParameterResolver implements ParameterResolver
22
{
23
    public function __construct(
24
        private ContainerInterface $container
25
    ) {
26
    }
27
 
28
    public function getParameters(
29
        ReflectionFunctionAbstract $reflection,
30
        array $providedParameters,
31
        array $resolvedParameters
32
    ) : array {
33
        $parameters = $reflection->getParameters();
34
 
35
        // Skip parameters already resolved
36
        if (! empty($resolvedParameters)) {
37
            $parameters = array_diff_key($parameters, $resolvedParameters);
38
        }
39
 
40
        foreach ($parameters as $index => $parameter) {
41
            $parameterType = $parameter->getType();
42
            if (!$parameterType) {
43
                // No type
44
                continue;
45
            }
46
            if (!$parameterType instanceof ReflectionNamedType) {
47
                // Union types are not supported
48
                continue;
49
            }
50
            if ($parameterType->isBuiltin()) {
51
                // Primitive types are not supported
52
                continue;
53
            }
54
 
55
            $parameterClass = $parameterType->getName();
56
 
57
            if ($parameterClass === 'Psr\Container\ContainerInterface') {
58
                $resolvedParameters[$index] = $this->container;
59
            } elseif ($parameterClass === 'DI\Factory\RequestedEntry') {
60
                // By convention the second parameter is the definition
61
                $resolvedParameters[$index] = $providedParameters[1];
62
            } elseif ($this->container->has($parameterClass)) {
63
                $resolvedParameters[$index] = $this->container->get($parameterClass);
64
            }
65
        }
66
 
67
        return $resolvedParameters;
68
    }
69
}