Completed
Push — master ( d7ac59...64fa5b )
by Matthieu
02:28
created

FactoryResolver::resolveExtraParams()   A

Complexity

Conditions 4
Paths 5

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 17
Code Lines 10

Importance

Changes 1
Bugs 1 Features 1
Metric Value
cc 4
eloc 10
c 1
b 1
f 1
nc 5
nop 1
dl 0
loc 17
rs 9.2
1
<?php
2
3
namespace DI\Definition\Resolver;
4
5
use DI\Definition\Definition;
6
use DI\Definition\Exception\DefinitionException;
7
use DI\Definition\FactoryDefinition;
8
use DI\Definition\Helper\DefinitionHelper;
9
use DI\Invoker\FactoryParameterResolver;
10
use Interop\Container\ContainerInterface;
11
use Invoker\Exception\NotCallableException;
12
use Invoker\Exception\NotEnoughParametersException;
13
use Invoker\Invoker;
14
use Invoker\ParameterResolver\AssociativeArrayResolver;
15
use Invoker\ParameterResolver\NumericArrayResolver;
16
use Invoker\ParameterResolver\ResolverChain;
17
18
/**
19
 * Resolves a factory definition to a value.
20
 *
21
 * @since 4.0
22
 * @author Matthieu Napoli <[email protected]>
23
 */
24
class FactoryResolver implements DefinitionResolver
25
{
26
    /**
27
     * @var ContainerInterface
28
     */
29
    private $container;
30
31
    /**
32
     * @var Invoker|null
33
     */
34
    private $invoker;
35
36
    /**
37
     * @var DefinitionResolver
38
     */
39
    private $resolver;
40
41
    /**
42
     * The resolver needs a container. This container will be passed to the factory as a parameter
43
     * so that the factory can access other entries of the container.
44
     *
45
     * @param ContainerInterface $container
46
     */
47
    public function __construct(ContainerInterface $container, DefinitionResolver $resolver)
48
    {
49
        $this->container = $container;
50
        $this->resolver = $resolver;
51
    }
52
53
    /**
54
     * Resolve a factory definition to a value.
55
     *
56
     * This will call the callable of the definition.
57
     *
58
     * @param FactoryDefinition $definition
59
     *
60
     * [email protected]}
61
     */
62
    public function resolve(Definition $definition, array $parameters = [])
63
    {
64
        if (! $this->invoker) {
65
            $parameterResolver = new ResolverChain([
66
               new FactoryParameterResolver($this->container),
67
               new AssociativeArrayResolver,
68
               new NumericArrayResolver,
69
            ]);
70
71
            $this->invoker = new Invoker($parameterResolver, $this->container);
72
        }
73
74
        $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...
75
76
        try {
77
            $providedParams = [$this->container, $definition];
78
            $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...
79
            $providedParams = array_merge($providedParams, $extraParams);
80
81
            return $this->invoker->call($callable, $providedParams);
82
        } catch (NotCallableException $e) {
83
            // Custom error message to help debugging
84
            if (is_string($callable) && class_exists($callable) && method_exists($callable, '__invoke')) {
85
                throw new DefinitionException(sprintf(
86
                    '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.',
87
                    $definition->getName(),
88
                    $e->getMessage()
89
                ));
90
            }
91
92
            throw new DefinitionException(sprintf(
93
                'Entry "%s" cannot be resolved: factory %s',
94
                $definition->getName(),
95
                $e->getMessage()
96
            ));
97
        } catch (NotEnoughParametersException $e) {
98
            throw new DefinitionException(sprintf(
99
                'Entry "%s" cannot be resolved: %s',
100
                $definition->getName(),
101
                $e->getMessage()
102
            ));
103
        }
104
    }
105
106
    /**
107
     * [email protected]}
108
     */
109
    public function isResolvable(Definition $definition, array $parameters = [])
110
    {
111
        return true;
112
    }
113
114
    private function resolveExtraParams(array $params)
115
    {
116
        $resolved = [];
117
        foreach ($params as $key => $value) {
118
            if ($value instanceof DefinitionHelper) {
119
                // As per ObjectCreator::injectProperty, use '' for an anonymous sub-definition
120
                $value = $value->getDefinition('');
121
            }
122
            if (!$value instanceof Definition) {
123
                $resolved[$key] = $value;
124
            } else {
125
                $resolved[$key] = $this->resolver->resolve($value);
126
            }
127
        }
128
129
        return $resolved;
130
    }
131
}
132