Completed
Pull Request — 1.0 (#8)
by David
02:19
created

ServiceProviderLoader::loadFromRegistry()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
declare (strict_types = 1);
4
5
namespace TheCodingMachine\Yaco\ServiceProvider;
6
7
use Interop\Container\Definition\DefinitionInterface;
8
use Interop\Container\ServiceProvider;
9
use TheCodingMachine\ServiceProvider\Registry;
10
use TheCodingMachine\Yaco\Compiler;
11
use TheCodingMachine\Yaco\CompilerException;
12
use TheCodingMachine\Yaco\Definition\AliasDefinition;
13
use TheCodingMachine\Yaco\Definition\DumpableInterface;
14
use TheCodingMachine\Yaco\Definition\FactoryCallDefinition;
15
use TheCodingMachine\Yaco\Definition\Reference;
16
use TheCodingMachine\Yaco\DefinitionConverterInterface;
17
18
class ServiceProviderLoader
19
{
20
    /**
21
     * @var Compiler
22
     */
23
    private $compiler;
24
25
    /**
26
     * @var DefinitionConverterInterface
27
     */
28
    private $converter;
29
30
    /**
31
     * @param Compiler $compiler
32
     */
33
    public function __construct(Compiler $compiler, DefinitionConverterInterface $converter)
34
    {
35
        $this->compiler = $compiler;
36
        $this->converter = $converter;
37
    }
38
39
    /**
40
     * Loads the registry into the container.
41
     *
42
     * @param Registry $registry
43
     */
44
    public function loadFromRegistry(Registry $registry)
45
    {
46
        foreach ($registry as $key => $serviceProvider) {
47
            $this->loadServiceProvider($serviceProvider, $key);
48
        }
49
    }
50
51
    /**
52
     * @param ServiceProvider $serviceProvider
53
     * @param int             $serviceProviderKey
54
     */
55
    private function loadServiceProvider(ServiceProvider $serviceProvider, $serviceProviderKey)
56
    {
57
        $serviceFactories = $serviceProvider->getServices();
58
59
        foreach ($serviceFactories as $serviceName => $callable) {
60
            $this->registerService($serviceName, $serviceProviderKey, $callable);
61
        }
62
    }
63
64
    /**
65
     * @param string          $serviceName
66
     * @param ServiceProvider $serviceProvider
0 ignored issues
show
Documentation introduced by
There is no parameter named $serviceProvider. Did you maybe mean $serviceProviderKey?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
67
     * @param int             $serviceProviderKey
68
     * @param callable        $callable
69
     *
70
     * @throws \TheCodingMachine\Yaco\CompilerException
71
     */
72
    private function registerService($serviceName, $serviceProviderKey, callable $callable)
73
    {
74
        if (!$this->compiler->has($serviceName)) {
75
            $definition = $this->getServiceDefinitionFromCallable($serviceName, $serviceName, $serviceProviderKey, $callable, new ContainerDefinition());
76
77
            $this->compiler->addDumpableDefinition($definition);
78
        } else {
79
            // The new service will be created under the name 'xxx_decorated_y'
80
            // The old service will be moved to the name 'xxx_decorated_y.inner'
81
            // This old service will be accessible through a callback represented by 'xxx_decorated_y.callbackwrapper'
82
            // The $servicename becomes an alias pointing to 'xxx_decorated_y'
83
84
            $previousDefinition = $this->compiler->getDumpableDefinition($serviceName);
85
            /*while ($previousDefinition instanceof Reference) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
86
                $previousDefinition = $this->compiler->getDumpableDefinition($previousDefinition->getAlias());
87
            }*/
88
89
            while ($previousDefinition instanceof AliasDefinition) {
90
                $previousDefinition = $this->compiler->getDumpableDefinition($previousDefinition->getAlias());
91
            }
92
93
            $oldServiceName = $serviceName;
94
            $decoratedServiceName = $this->getDecoratedServiceName($serviceName);
95
            $innerName = $decoratedServiceName.'.inner';
96
            $callbackWrapperName = $decoratedServiceName.'.callbackwrapper';
97
98
            // TODO: it would be way easier if we could simply rename a definition!!!
99
            if ($previousDefinition instanceof FactoryCallDefinition) {
100
                $innerDefinition = new FactoryCallDefinition($innerName, $previousDefinition->getFactory(), $previousDefinition->getMethodName(), $previousDefinition->getMethodArguments());
101
                // @codeCoverageIgnoreStart
102
            } elseif ($previousDefinition instanceof ServiceFromRegistryDefinition) {
103
                // @codeCoverageIgnoreEnd
104
                $innerDefinition = new ServiceFromRegistryDefinition($innerName, $previousDefinition->getServiceName(), $previousDefinition->getServiceProviderKey(), $previousDefinition->getCallbackWrapperDefinition());
105
            } else {
106
                // @codeCoverageIgnoreStart
107
                throw new CompilerException('Unable to rename definition from class '.get_class($previousDefinition));
108
                // @codeCoverageIgnoreEnd
109
            }
110
111
            $callbackWrapperDefinition = new CallbackWrapperDefinition($callbackWrapperName, $innerDefinition);
112
113
            $definition = $this->getServiceDefinitionFromCallable($decoratedServiceName, $serviceName, $serviceProviderKey, $callable, new ContainerDefinition(), $callbackWrapperDefinition);
114
115
            $this->compiler->addDumpableDefinition($definition);
116
            $this->compiler->addDumpableDefinition($innerDefinition);
117
            $this->compiler->addDumpableDefinition($callbackWrapperDefinition);
118
            $this->compiler->addDumpableDefinition(new AliasDefinition($oldServiceName, $decoratedServiceName));
119
        }
120
    }
121
122
    /**
123
     * @param $serviceName
124
     * @param int                            $serviceProviderKey
125
     * @param callable                       $callable
126
     * @param ContainerDefinition            $containerDefinition
127
     * @param CallbackWrapperDefinition|null $callbackWrapperDefinition
128
     *
129
     * @return DumpableInterface
130
     */
131
    private function getServiceDefinitionFromCallable($decoratedServiceName, $serviceName, $serviceProviderKey, callable $callable, ContainerDefinition $containerDefinition, CallbackWrapperDefinition $callbackWrapperDefinition = null)
132
    {
133
        if ($callable instanceof DefinitionInterface) {
134
            return $this->converter->convert($decoratedServiceName, $callable);
135
        }
136
        if (is_array($callable) && is_string($callable[0])) {
137
            $params = [$containerDefinition];
138
            if ($callbackWrapperDefinition) {
139
                $params[] = $callbackWrapperDefinition;
140
            }
141
142
            return new FactoryCallDefinition($decoratedServiceName, $callable[0], $callable[1], $params);
0 ignored issues
show
Documentation introduced by
$callable[0] is of type string, but the function expects a object<TheCodingMachine\...ion\ReferenceInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
143
        } elseif (is_string($callable) && strpos($callable, '::') !== false) {
144
            $pos = strpos($callable, '::');
145
            $className = substr($callable, 0, $pos);
146
            $methodName = substr($callable, $pos + 2);
147
            $params = [$containerDefinition];
148
            if ($callbackWrapperDefinition) {
149
                $params[] = $callbackWrapperDefinition;
150
            }
151
152
            return new FactoryCallDefinition($decoratedServiceName, $className, $methodName, $params);
0 ignored issues
show
Documentation introduced by
$className is of type string, but the function expects a object<TheCodingMachine\...ion\ReferenceInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
153
        }
154
155
        // This is an object or a callback... we need to call the getServices method of the service provider at runtime.
156
        return new ServiceFromRegistryDefinition($decoratedServiceName, $serviceName, $serviceProviderKey, $callbackWrapperDefinition);
157
    }
158
159
    /**
160
     * @param string $serviceName
161
     *
162
     * @return string
163
     */
164
    private function getDecoratedServiceName($serviceName)
165
    {
166
        $counter = 1;
167
        while ($this->compiler->has($serviceName.'_decorated_'.$counter)) {
168
            ++$counter;
169
        }
170
171
        return $serviceName.'_decorated_'.$counter;
172
    }
173
}
174