Completed
Pull Request — 1.0 (#1)
by David
10:52 queued 59s
created

ServiceProviderCompilationPass::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
rs 9.4285
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