Completed
Pull Request — 1.0 (#8)
by David
06:24
created

ServiceProviderLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
declare(strict_types=1);
3
4
namespace TheCodingMachine\Yaco\ServiceProvider;
5
6
7
use Interop\Container\Definition\DefinitionInterface;
8
use Interop\Container\ServiceProvider;
9
use Puli\Discovery\Api\Discovery;
10
use Puli\Discovery\Binding\ClassBinding;
11
use TheCodingMachine\ServiceProvider\Registry;
12
use TheCodingMachine\Yaco\Compiler;
13
use TheCodingMachine\Yaco\CompilerException;
14
use TheCodingMachine\Yaco\Definition\AliasDefinition;
15
use TheCodingMachine\Yaco\Definition\DumpableInterface;
16
use TheCodingMachine\Yaco\Definition\FactoryCallDefinition;
17
use TheCodingMachine\Yaco\Definition\Reference;
18
use TheCodingMachine\Yaco\DefinitionConverter;
19
use TheCodingMachine\Yaco\DefinitionConverterInterface;
20
21
class ServiceProviderLoader
22
{
23
    /**
24
     * @var Compiler
25
     */
26
    private $compiler;
27
28
    /**
29
     * @var DefinitionConverterInterface
30
     */
31
    private $converter;
32
33
    /**
34
     * @param Compiler $compiler
35
     */
36
    public function __construct(Compiler $compiler, DefinitionConverterInterface $converter)
37
    {
38
        $this->compiler = $compiler;
39
        $this->converter = $converter;
40
    }
41
42
    /**
43
     * Loads the registry into the container.
44
     * @param Registry $registry
45
     */
46
    public function loadFromRegistry(Registry $registry) {
47
        foreach ($registry as $key => $serviceProvider) {
48
            $this->loadServiceProvider($serviceProvider, $key);
49
        }
50
    }
51
52
    /**
53
     * @param ServiceProvider $serviceProvider
54
     * @param int $serviceProviderKey
55
     */
56
    private function loadServiceProvider(ServiceProvider $serviceProvider, $serviceProviderKey)
57
    {
58
        $serviceFactories = $serviceProvider->getServices();
59
60
        foreach ($serviceFactories as $serviceName => $callable) {
61
            $this->registerService($serviceName, $serviceProviderKey, $callable);
62
        }
63
    }
64
65
    /**
66
     * @param string $serviceName
67
     * @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...
68
     * @param int $serviceProviderKey
69
     * @param callable $callable
70
     * @throws \TheCodingMachine\Yaco\CompilerException
71
     */
72
    private function registerService($serviceName, $serviceProviderKey, callable $callable) {
73
        if (!$this->compiler->has($serviceName)) {
74
            $definition = $this->getServiceDefinitionFromCallable($serviceName, $serviceName, $serviceProviderKey, $callable, new ContainerDefinition());
75
76
            $this->compiler->addDumpableDefinition($definition);
77
        } else {
78
            // The new service will be created under the name 'xxx_decorated_y'
79
            // The old service will be moved to the name 'xxx_decorated_y.inner'
80
            // This old service will be accessible through a callback represented by 'xxx_decorated_y.callbackwrapper'
81
            // The $servicename becomes an alias pointing to 'xxx_decorated_y'
82
83
            $previousDefinition = $this->compiler->getDumpableDefinition($serviceName);
84
            /*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...
85
                $previousDefinition = $this->compiler->getDumpableDefinition($previousDefinition->getAlias());
86
            }*/
87
88
            while ($previousDefinition instanceof AliasDefinition) {
89
                $previousDefinition = $this->compiler->getDumpableDefinition($previousDefinition->getAlias());
90
            }
91
92
            $oldServiceName = $serviceName;
93
            $decoratedServiceName = $this->getDecoratedServiceName($serviceName);
94
            $innerName = $decoratedServiceName.'.inner';
95
            $callbackWrapperName = $decoratedServiceName.'.callbackwrapper';
96
97
            // TODO: it would be way easier if we could simply rename a definition!!!
98
            if ($previousDefinition instanceof FactoryCallDefinition) {
99
                $innerDefinition = new FactoryCallDefinition($innerName, $previousDefinition->getFactory(), $previousDefinition->getMethodName(), $previousDefinition->getMethodArguments());
100
                // @codeCoverageIgnoreStart
101
            } elseif ($previousDefinition instanceof ServiceFromRegistryDefinition) {
102
                // @codeCoverageIgnoreEnd
103
                $innerDefinition = new ServiceFromRegistryDefinition($innerName, $previousDefinition->getServiceName(), $previousDefinition->getServiceProviderKey(), $previousDefinition->getCallbackWrapperDefinition());
104
            } else {
105
                // @codeCoverageIgnoreStart
106
                throw new CompilerException('Unable to rename definition from class '.get_class($previousDefinition));
107
                // @codeCoverageIgnoreEnd
108
            }
109
110
111
112
            $callbackWrapperDefinition = new CallbackWrapperDefinition($callbackWrapperName, $innerDefinition);
113
114
            $definition = $this->getServiceDefinitionFromCallable($decoratedServiceName, $serviceName, $serviceProviderKey, $callable, new ContainerDefinition(), $callbackWrapperDefinition);
115
116
            $this->compiler->addDumpableDefinition($definition);
117
            $this->compiler->addDumpableDefinition($innerDefinition);
118
            $this->compiler->addDumpableDefinition($callbackWrapperDefinition);
119
            $this->compiler->addDumpableDefinition(new AliasDefinition($oldServiceName, $decoratedServiceName));
120
        }
121
122
    }
123
124
    /**
125
     * @param $serviceName
126
     * @param int $serviceProviderKey
127
     * @param callable $callable
128
     * @param ContainerDefinition $containerDefinition
129
     * @param CallbackWrapperDefinition|null $callbackWrapperDefinition
130
     * @return DumpableInterface
131
     */
132
    private function getServiceDefinitionFromCallable($decoratedServiceName, $serviceName, $serviceProviderKey, callable $callable, ContainerDefinition $containerDefinition, CallbackWrapperDefinition $callbackWrapperDefinition = null) {
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
            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...
142
        } elseif (is_string($callable) && strpos($callable, '::') !== false) {
143
            $pos = strpos($callable, '::');
144
            $className = substr($callable, 0, $pos);
145
            $methodName = substr($callable, $pos+2);
146
            $params = [ $containerDefinition ];
147
            if ($callbackWrapperDefinition) {
148
                $params[] = $callbackWrapperDefinition;
149
            }
150
            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...
151
        }
152
153
        // This is an object or a callback... we need to call the getServices method of the service provider at runtime.
154
        return new ServiceFromRegistryDefinition($decoratedServiceName, $serviceName, $serviceProviderKey, $callbackWrapperDefinition);
155
    }
156
157
    /**
158
     * @param string $serviceName
159
     * @return string
160
     */
161
    private function getDecoratedServiceName($serviceName) {
162
        $counter = 1;
163
        while ($this->compiler->has($serviceName.'_decorated_'.$counter)) {
164
            $counter++;
165
        }
166
        return $serviceName.'_decorated_'.$counter;
167
    }
168
}