Completed
Push — master ( b7a913...d7966f )
by Matthieu
07:52 queued 05:38
created

FactoryResolver::resolveExtraParams()   B

Complexity

Conditions 5
Paths 7

Duplication

Lines 7
Ratio 35 %

Size

Total Lines 20
Code Lines 12

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 7
nop 1
dl 7
loc 20
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DI\Definition\Resolver;
6
7
use DI\Definition\ArrayDefinition;
8
use DI\Definition\Definition;
9
use DI\Definition\Exception\InvalidDefinition;
10
use DI\Definition\FactoryDefinition;
11
use DI\Definition\Helper\DefinitionHelper;
12
use DI\Invoker\FactoryParameterResolver;
13
use Invoker\Exception\NotCallableException;
14
use Invoker\Exception\NotEnoughParametersException;
15
use Invoker\Invoker;
16
use Invoker\ParameterResolver\AssociativeArrayResolver;
17
use Invoker\ParameterResolver\NumericArrayResolver;
18
use Invoker\ParameterResolver\ResolverChain;
19
use Psr\Container\ContainerInterface;
20
21
/**
22
 * Resolves a factory definition to a value.
23
 *
24
 * @since 4.0
25
 * @author Matthieu Napoli <[email protected]>
26
 */
27
class FactoryResolver implements DefinitionResolver
28
{
29
    /**
30
     * @var ContainerInterface
31
     */
32
    private $container;
33
34
    /**
35
     * @var Invoker|null
36
     */
37
    private $invoker;
38
39
    /**
40
     * @var DefinitionResolver
41
     */
42
    private $resolver;
43
44
    /**
45
     * The resolver needs a container. This container will be passed to the factory as a parameter
46
     * so that the factory can access other entries of the container.
47
     */
48
    public function __construct(ContainerInterface $container, DefinitionResolver $resolver)
49
    {
50
        $this->container = $container;
51
        $this->resolver = $resolver;
52
    }
53
54
    /**
55
     * Resolve a factory definition to a value.
56
     *
57
     * This will call the callable of the definition.
58
     *
59
     * @param FactoryDefinition $definition
60
     *
61
     * {@inheritdoc}
62
     */
63
    public function resolve(Definition $definition, array $parameters = [])
64
    {
65
        if (! $this->invoker) {
66
            $parameterResolver = new ResolverChain([
67
               new AssociativeArrayResolver,
68
               new FactoryParameterResolver($this->container),
69
               new NumericArrayResolver,
70
            ]);
71
72
            $this->invoker = new Invoker($parameterResolver, $this->container);
73
        }
74
75
        $callable = $definition->getCallable();
0 ignored issues
show
Bug introduced by Matthieu Napoli
It seems like you code against a concrete implementation and not the interface DI\Definition\Definition as the method getCallable() does only exist in the following implementations of said interface: DI\Definition\DecoratorDefinition, DI\Definition\FactoryDefinition.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
76
77
        try {
78
            $providedParams = [$this->container, $definition];
79
            $extraParams = $this->resolveExtraParams($definition->getParameters());
0 ignored issues
show
Bug introduced by predakanga
It seems like you code against a concrete implementation and not the interface DI\Definition\Definition as the method getParameters() does only exist in the following implementations of said interface: DI\Definition\DecoratorDefinition, DI\Definition\FactoryDefinition, DI\Definition\ObjectDefinition\MethodInjection.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
80
            $providedParams = array_merge($providedParams, $extraParams);
81
82
            return $this->invoker->call($callable, $providedParams);
83
        } catch (NotCallableException $e) {
84
            // Custom error message to help debugging
85
            if (is_string($callable) && class_exists($callable) && method_exists($callable, '__invoke')) {
86
                throw new InvalidDefinition(sprintf(
87
                    'Entry "%s" cannot be resolved: factory %s. Invokable classes cannot be automatically resolved if autowiring is disabled on the container, you need to enable autowiring or define the entry manually.',
88
                    $definition->getName(),
89
                    $e->getMessage()
90
                ));
91
            }
92
93
            throw new InvalidDefinition(sprintf(
94
                'Entry "%s" cannot be resolved: factory %s',
95
                $definition->getName(),
96
                $e->getMessage()
97
            ));
98
        } catch (NotEnoughParametersException $e) {
99
            throw new InvalidDefinition(sprintf(
100
                'Entry "%s" cannot be resolved: %s',
101
                $definition->getName(),
102
                $e->getMessage()
103
            ));
104
        }
105
    }
106
107
    public function isResolvable(Definition $definition, array $parameters = []) : bool
108
    {
109
        return true;
110
    }
111
112
    private function resolveExtraParams(array $params) : array
113
    {
114
        $resolved = [];
115
        foreach ($params as $key => $value) {
116 View Code Duplication
            if ($value instanceof DefinitionHelper) {
117
                // As per ObjectCreator::injectProperty, use '' for an anonymous sub-definition
118
                $value = $value->getDefinition('');
119
            } elseif (is_array($value)) {
120
                // Cast arrays into array definitions to allow resolution of nested definitions
121
                $value = new ArrayDefinition('', $value);
122
            }
123
            if (!$value instanceof Definition) {
124
                $resolved[$key] = $value;
125
            } else {
126
                $resolved[$key] = $this->resolver->resolve($value);
127
            }
128
        }
129
130
        return $resolved;
131
    }
132
}
133