Completed
Pull Request — 1.1 (#10)
by David
07:43
created

ServiceProviderLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
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\ServiceProviderInterface;
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 ServiceProviderInterface $serviceProvider
53
     * @param int             $serviceProviderKey
54
     */
55
    private function loadServiceProvider(ServiceProviderInterface $serviceProvider, $serviceProviderKey)
56
    {
57
        $serviceFactories = $serviceProvider->getFactories();
58
59
        foreach ($serviceFactories as $serviceName => $callable) {
60
            $this->registerService($serviceName, $serviceProviderKey, $callable);
61
        }
62
63
        $serviceExtensions = $serviceProvider->getExtensions();
64
65
        foreach ($serviceExtensions as $serviceName => $callable) {
66
            $this->extendService($serviceName, $serviceProviderKey, $callable);
67
        }
68
    }
69
70
    /**
71
     * @param string $serviceName
72
     * @param int $serviceProviderKey
73
     * @param callable $callable
74
     *
75
     */
76
    private function registerService(string $serviceName, int $serviceProviderKey, callable $callable)
77
    {
78
        $definition = $this->getCreateServiceDefinitionFromCallable($serviceName, $serviceName, $serviceProviderKey, $callable, new ContainerDefinition());
79
80
        $this->compiler->addDumpableDefinition($definition);
81
    }
82
83
    /**
84
     * @param string $serviceName
85
     * @param int $serviceProviderKey
86
     * @param callable $callable
87
     *
88
     * @throws CompilerException
89
     */
90
    private function extendService(string $serviceName, int $serviceProviderKey, callable $callable)
91
    {
92
        // TODO: check if $callable as a nullable previous argument!
93
94
        if (!$this->compiler->has($serviceName)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
95
            // TODO: if $callable as NOT a nullable previous argument, throw an exception.
96
        }
97
98
        // The new service will be created under the name 'xxx_decorated_y'
99
        // The old service will be moved to the name 'xxx_decorated_y.inner'
100
        // This old service will be accessible through a callback represented by 'xxx_decorated_y.callbackwrapper'
101
        // The $servicename becomes an alias pointing to 'xxx_decorated_y'
102
103
        $previousDefinition = $this->compiler->getDumpableDefinition($serviceName);
104
        /*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...
105
            $previousDefinition = $this->compiler->getDumpableDefinition($previousDefinition->getAlias());
106
        }*/
107
108
        while ($previousDefinition instanceof AliasDefinition) {
109
            $previousDefinition = $this->compiler->getDumpableDefinition($previousDefinition->getAlias());
110
        }
111
112
        $oldServiceName = $serviceName;
113
        $decoratedServiceName = $this->getDecoratedServiceName($serviceName);
114
        //$innerName = $decoratedServiceName.'.inner';
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
115
        //$callbackWrapperName = $decoratedServiceName.'.callbackwrapper';
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
116
117
        // TODO: it would be way easier if we could simply rename a definition!!!
118
        if ($previousDefinition instanceof FactoryCallDefinition) {
119
            $innerDefinition = new FactoryCallDefinition(null /*$innerName*/, $previousDefinition->getFactory(), $previousDefinition->getMethodName(), $previousDefinition->getMethodArguments());
0 ignored issues
show
Bug introduced by
It seems like $previousDefinition->getFactory() targeting TheCodingMachine\Yaco\De...efinition::getFactory() can also be of type string; however, TheCodingMachine\Yaco\De...finition::__construct() does only seem to accept object<TheCodingMachine\...ion\ReferenceInterface>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
120
        } elseif ($previousDefinition instanceof CreateServiceFromRegistryDefinition || $previousDefinition instanceof ExtendServiceFromRegistryDefinition) {
121
            $innerDefinition = $previousDefinition;
122
        } else {
123
            // @codeCoverageIgnoreStart
124
            throw new CompilerException('Unable to rename definition from class '.get_class($previousDefinition));
125
            // @codeCoverageIgnoreEnd
126
        }
127
128
        $definition = $this->getExtendServiceDefinitionFromCallable($decoratedServiceName, $serviceName, $serviceProviderKey, $callable, new ContainerDefinition(), $innerDefinition);
129
130
        $this->compiler->addDumpableDefinition($definition);
131
        //$this->compiler->addDumpableDefinition($innerDefinition);
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% 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...
132
        //$this->compiler->addDumpableDefinition($callbackWrapperDefinition);
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% 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...
133
        $this->compiler->addDumpableDefinition(new AliasDefinition($oldServiceName, $decoratedServiceName));
134
    }
135
136
    /**
137
     * @param $serviceName
138
     * @param int                            $serviceProviderKey
139
     * @param callable                       $callable
140
     * @param ContainerDefinition            $containerDefinition
141
     *
142
     * @return DumpableInterface
143
     */
144
    private function getCreateServiceDefinitionFromCallable($decoratedServiceName, $serviceName, $serviceProviderKey, callable $callable, ContainerDefinition $containerDefinition): DumpableInterface
145
    {
146
        // FIXME: we must split this method in 2. One for the factories and one for the extensions!
147
148
        if ($callable instanceof DefinitionInterface) {
149
            return $this->converter->convert($decoratedServiceName, $callable);
150
        }
151 View Code Duplication
        if (is_array($callable) && is_string($callable[0])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
152
            return new FactoryCallDefinition($decoratedServiceName, $callable[0], $callable[1], [$containerDefinition]);
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...
153
        } elseif (is_string($callable) && strpos($callable, '::') !== false) {
154
            $pos = strpos($callable, '::');
155
            $className = substr($callable, 0, $pos);
156
            $methodName = substr($callable, $pos + 2);
157
158
            return new FactoryCallDefinition($decoratedServiceName, $className, $methodName, [$containerDefinition]);
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...
159
        }
160
161
        // This is an object or a callback... we need to call the getServices method of the service provider at runtime.
162
        return new CreateServiceFromRegistryDefinition($decoratedServiceName, $serviceName, $serviceProviderKey);
163
    }
164
165
    /**
166
     * @param $serviceName
167
     * @param int                            $serviceProviderKey
168
     * @param callable                       $callable
169
     * @param ContainerDefinition            $containerDefinition
170
     * @param CallbackWrapperDefinition|null $previousDefinition
171
     *
172
     * @return DumpableInterface
173
     */
174
    private function getExtendServiceDefinitionFromCallable($decoratedServiceName, $serviceName, $serviceProviderKey, callable $callable, ContainerDefinition $containerDefinition, DumpableInterface $previousDefinition = null)
175
    {
176
        // FIXME: we must split this method in 2. One for the factories and one for the extensions!
177
178
        if ($callable instanceof DefinitionInterface) {
179
            return $this->converter->convert($decoratedServiceName, $callable);
180
        }
181 View Code Duplication
        if (is_array($callable) && is_string($callable[0])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
182
            return new FactoryCallDefinition($decoratedServiceName, $callable[0], $callable[1], [$containerDefinition, $previousDefinition]);
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...
183
        } elseif (is_string($callable) && strpos($callable, '::') !== false) {
184
            $pos = strpos($callable, '::');
185
            $className = substr($callable, 0, $pos);
186
            $methodName = substr($callable, $pos + 2);
187
188
            return new FactoryCallDefinition($decoratedServiceName, $className, $methodName, [$containerDefinition, $previousDefinition]);
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...
189
        }
190
191
        // This is an object or a callback... we need to call the getServices method of the service provider at runtime.
192
        return new ExtendServiceFromRegistryDefinition($decoratedServiceName, $serviceName, $serviceProviderKey, $previousDefinition);
193
    }
194
195
    /**
196
     * @param string $serviceName
197
     *
198
     * @return string
199
     */
200
    private function getDecoratedServiceName($serviceName)
201
    {
202
        $counter = 1;
203
        while ($this->compiler->has($serviceName.'_decorated_'.$counter)) {
204
            ++$counter;
205
        }
206
207
        return $serviceName.'_decorated_'.$counter;
208
    }
209
}
210