Completed
Pull Request — 1.0 (#1)
by David
09:17
created

ServiceProviderCompilationPass   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 138
Duplicated Lines 10.14 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 14
loc 138
rs 10
c 2
b 0
f 0
wmc 19
lcom 1
cbo 6

10 Methods

Rating   Name   Duplication   Size   Complexity  
A registerRegistry() 0 7 1
A registerAcclimatedContainer() 0 6 1
A __construct() 0 5 1
A process() 0 22 3
A registerFactories() 7 7 2
A registerExtensions() 7 7 2
A registerService() 0 5 1
B extendService() 0 26 2
A getDecoratedServiceName() 0 7 2
A getServiceDefinitionFromCallable() 0 20 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
4
namespace TheCodingMachine\Interop\ServiceProviderBridgeBundle;
5
6
7
use Interop\Container\ServiceProviderInterface;
8
use Symfony\Component\DependencyInjection\Alias;
9
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
10
use Symfony\Component\DependencyInjection\ContainerBuilder;
11
use Symfony\Component\DependencyInjection\Definition;
12
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
13
use Symfony\Component\DependencyInjection\Reference;
14
use TheCodingMachine\ServiceProvider\Registry;
15
16
class ServiceProviderCompilationPass implements CompilerPassInterface
17
{
18
    private $registryId;
19
20
    private $registryProvider;
21
22
    /**
23
     * @param int $registryId
24
     * @param RegistryProviderInterface $registryProvider
25
     */
26
    public function __construct($registryId, RegistryProviderInterface $registryProvider)
27
    {
28
        $this->registryId = $registryId;
29
        $this->registryProvider = $registryProvider;
30
    }
31
32
    /**
33
     * You can modify the container here before it is dumped to PHP code.
34
     *
35
     * @param ContainerBuilder $container
36
     */
37
    public function process(ContainerBuilder $container)
38
    {
39
        // Now, let's store the registry in the container (an empty version of it... it will be dynamically added at runtime):
40
        $this->registerRegistry($container);
41
42
        $registry = $this->registryProvider->getRegistry($container);
43
44
        // Note: in the 'boot' method of a bundle, the container is available.
45
        // We use that to push the lazy array in the container.
46
        // The lazy array can be used by the registry that is also part of the container.
47
        // The registry can itself be used by a factory that creates services!
48
49
        $this->registerAcclimatedContainer($container);
50
51
        foreach ($registry as $serviceProviderKey => $serviceProvider) {
52
            $this->registerFactories($serviceProviderKey, $serviceProvider, $container);
53
        }
54
55
        foreach ($registry as $serviceProviderKey => $serviceProvider) {
56
            $this->registerExtensions($serviceProviderKey, $serviceProvider, $container);
57
        }
58
    }
59
60
61
    private function registerRegistry(ContainerBuilder $container)
62
    {
63
        $definition = new Definition(Registry::class);
64
        $definition->setSynthetic(true);
65
66
        $container->setDefinition('service_provider_registry_'.$this->registryId, $definition);
67
    }
68
69
    private function registerAcclimatedContainer(ContainerBuilder $container) {
70
        $definition = new Definition('TheCodingMachine\\Interop\\ServiceProviderBridgeBundle\\SymfonyContainerAdapter');
71
        $definition->addArgument(new Reference("service_container"));
72
73
        $container->setDefinition('interop_service_provider_acclimated_container', $definition);
74
    }
75
76 View Code Duplication
    private function registerFactories($serviceProviderKey, ServiceProviderInterface $serviceProvider, ContainerBuilder $container) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
77
        $serviceFactories = $serviceProvider->getFactories();
78
79
        foreach ($serviceFactories as $serviceName => $callable) {
80
            $this->registerService($serviceName, $serviceProviderKey, $callable, $container);
81
        }
82
    }
83
84 View Code Duplication
    private function registerExtensions($serviceProviderKey, ServiceProviderInterface $serviceProvider, ContainerBuilder $container) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
85
        $serviceFactories = $serviceProvider->getExtensions();
86
87
        foreach ($serviceFactories as $serviceName => $callable) {
88
            $this->extendService($serviceName, $serviceProviderKey, $callable, $container);
89
        }
90
    }
91
92
    private function registerService($serviceName, $serviceProviderKey, $callable, ContainerBuilder $container) {
93
        $factoryDefinition = $this->getServiceDefinitionFromCallable($serviceName, $serviceProviderKey, $callable);
94
95
        $container->setDefinition($serviceName, $factoryDefinition);
96
    }
97
98
    private function extendService($serviceName, $serviceProviderKey, $callable, ContainerBuilder $container) {
99
        $factoryDefinition = $this->getServiceDefinitionFromCallable($serviceName, $serviceProviderKey, $callable);
100
101
        if (!$container->has($serviceName)) {
102
            $container->setDefinition($serviceName, $factoryDefinition);
103
        } else {
104
            // The new service will be created under the name 'xxx_decorated_y'
105
            // The old service will be moved to the name 'xxx_decorated_y.inner'
106
            // This old service will be accessible through a callback represented by 'xxx_decorated_y.callbackwrapper'
107
            // The $servicename becomes an alias pointing to 'xxx_decorated_y'
108
109
            $oldServiceName = $serviceName;
110
            $serviceName = $this->getDecoratedServiceName($serviceName, $container);
111
112
            $innerName = $serviceName.'.inner';
113
            $innerDefinition = $container->findDefinition($oldServiceName);
114
            $container->setDefinition($innerName, $innerDefinition);
115
116
            $factoryDefinition->addArgument(new Reference($innerName));
117
118
            $container->setDefinition($serviceName, $factoryDefinition);
119
            $container->setDefinition($innerName, $innerDefinition);
120
121
            $container->setAlias($oldServiceName, new Alias($serviceName));
122
        }
123
    }
124
125
    private function getDecoratedServiceName($serviceName, ContainerBuilder $container) {
126
        $counter = 1;
127
        while ($container->has($serviceName.'_decorated_'.$counter)) {
128
            $counter++;
129
        }
130
        return $serviceName.'_decorated_'.$counter;
131
    }
132
133
    private function getServiceDefinitionFromCallable($serviceName, $serviceProviderKey, callable $callable)
134
    {
135
        /*if ($callable instanceof DefinitionInterface) {
136
            // TODO: plug the definition-interop converter here!
137
        }*/
138
        $factoryDefinition = new Definition('Class'); // TODO: in PHP7, we can get the return type of the function!
139
        $containerDefinition = new Reference('interop_service_provider_acclimated_container');
140
141
        if ((is_array($callable) && is_string($callable[0])) || is_string($callable)) {
142
            $factoryDefinition->setFactory($callable);
143
            $factoryDefinition->addArgument(new Reference('interop_service_provider_acclimated_container'));
144
        } else {
145
            $factoryDefinition->setFactory([ new Reference('service_provider_registry_'.$this->registryId), 'createService' ]);
146
            $factoryDefinition->addArgument($serviceProviderKey);
147
            $factoryDefinition->addArgument($serviceName);
148
            $factoryDefinition->addArgument($containerDefinition);
149
        }
150
151
        return $factoryDefinition;
152
    }
153
}
154