Failed Conditions
Push — feature/improve ( 72ac1b...48dfdf )
by Yo
02:23
created

KernelSubExtension::configure()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 43
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 43
ccs 0
cts 0
cp 0
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 38
nc 1
nop 1
crap 6
1
<?php
2
namespace Yoanm\Behat3SymfonyExtension\ServiceContainer\SubExtension;
3
4
use Behat\MinkExtension\ServiceContainer\MinkExtension;
5
use Behat\Testwork\EventDispatcher\ServiceContainer\EventDispatcherExtension;
6
use Behat\Testwork\ServiceContainer\Exception\ProcessingException;
7
use Behat\Testwork\ServiceContainer\ExtensionManager;
8
use Symfony\Component\BrowserKit\CookieJar;
9
use Symfony\Component\BrowserKit\History;
10
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
11
use Symfony\Component\DependencyInjection\ContainerBuilder;
12
use Symfony\Component\DependencyInjection\Definition;
13
use Symfony\Component\DependencyInjection\Reference;
14
use Yoanm\Behat3SymfonyExtension\Client\Client;
15
use Yoanm\Behat3SymfonyExtension\Context\Initializer\KernelAwareInitializer;
16
use Yoanm\Behat3SymfonyExtension\Context\Initializer\KernelHandlerAwareInitializer;
17
use Yoanm\Behat3SymfonyExtension\Dispatcher\BehatKernelEventDispatcher;
18
use Yoanm\Behat3SymfonyExtension\Factory\KernelFactory;
19
use Yoanm\Behat3SymfonyExtension\Handler\KernelHandler;
20
use Yoanm\Behat3SymfonyExtension\ServiceContainer\AbstractExtension;
21
use Yoanm\Behat3SymfonyExtension\ServiceContainer\DriverFactory\Behat3SymfonyFactory;
22
use Yoanm\Behat3SymfonyExtension\Subscriber\RebootKernelSubscriber;
23
24
class KernelSubExtension extends AbstractExtension
25
{
26
    /**
27
     * @inheritDoc
28
     */
29 3
    public function getConfigKey()
30
    {
31 3
        return 'kernel';
32
    }
33
34
    // @codeCoverageIgnoreStart
35
    // Not possible to cover this because ExtensionManager is a final class
36
    /**
37
     * @inheritDoc
38
     */
39
    public function initialize(ExtensionManager $extensionManager)
40
    {
41
        $minExtension = $extensionManager->getExtension('mink');
42
        if ($minExtension instanceof MinkExtension) {
43
            $minExtension->registerDriverFactory(new Behat3SymfonyFactory());
44
        }
45
    }
46
    // @codeCoverageIgnoreEnd
47
48
    // @codeCoverageIgnoreStart
49
    // Will be covered by FT
50
    /**
51
     * @inheritDoc
52
     */
53
    public function configure(ArrayNodeDefinition $builder)
54
    {
55
        $castToBool = function ($value) {
56
            $filtered = filter_var(
57
                $value,
58
                FILTER_VALIDATE_BOOLEAN,
59
                FILTER_NULL_ON_FAILURE
60
            );
61
62
            return (null === $filtered) ? (bool) $value : $filtered;
63
        };
64
        $builder
65
            ->addDefaultsIfNotSet()
66
            ->children()
67
                ->scalarNode('bootstrap')
68
                    ->defaultValue('app/autoload.php')
69
                ->end()
70
                ->scalarNode('path')
71
                    ->defaultValue('app/AppKernel.php')
72
                ->end()
73
                ->scalarNode('class')
74
                    ->defaultValue('AppKernel')
75
                ->end()
76
                ->scalarNode('env')
77
                    ->defaultValue('test')
78
                ->end()
79
                ->booleanNode('debug')
80
                    ->beforeNormalization()
81
                    ->always()
82
                        ->then($castToBool)
83
                    ->end()
84
                    ->defaultTrue()
85
                ->end()
86
                ->booleanNode('reboot')
87
                    ->info('If true symfony kernel will be rebooted after each scenario/example')
88
                    ->beforeNormalization()
89
                        ->always()
90
                        ->then($castToBool)
91
                    ->end()
92
                    ->defaultTrue()
93
                ->end()
94
            ->end();
95
    }
96
    // @codeCoverageIgnoreEnd
97
98
    /**
99
     * {@inheritdoc}
100
     */
101 2
    public function load(ContainerBuilder $container, array $config)
102
    {
103 2
        $kernelConfig = $config[$this->getConfigKey()];
104
105 2
        $this->loadContainerParameter($container, $kernelConfig);
106 2
        $this->loadInitializer($container);
107 2
        $this->loadSubscriber($container, $kernelConfig);
108 2
        $this->createService(
109 2
            $container,
110 2
            'test.client',
111 2
            Client::class,
112
            [
113 2
                    new Reference($this->buildContainerId('handler.kernel')),
114 2
                    new Reference(self::KERNEL_SERVICE_ID),
115 2
                    [],
116 2
                    new Reference($this->buildContainerId('test.client.history')),
117 2
                    new Reference($this->buildContainerId('test.client.cookiejar'))
118 2
                ]
119 2
        );
120 2
        $this->createService(
121 2
            $container,
122 2
            'test.client.history',
123
            History::class
124 2
        );
125 2
        $this->createService(
126 2
            $container,
127 2
            'test.client.cookiejar',
128
            CookieJar::class
129 2
        );
130 2
        $this->createService(
131 2
            $container,
132 2
            'handler.kernel',
133 2
            KernelHandler::class,
134
            [
135 2
                new Reference('event_dispatcher'),
136 2
                new Reference(self::KERNEL_SERVICE_ID),
137
            ]
138 2
        );
139 2
        $this->createService(
140 2
            $container,
141 2
            'dispatcher.kernel_event',
142 2
            BehatKernelEventDispatcher::class,
143 2
            [new Reference('event_dispatcher')]
144 2
        );
145
        // Load Kernel thanks to the factory
146 2
        $this->createService(
147 2
            $container,
148 2
            'kernel',
149 2
            $kernelConfig['class'],
150 2
            [],
151 2
            [],
152 2
            [],
153 2
            [new Reference($this->buildContainerId('factory.kernel')), 'load']
154 2
        );
155
156 2
        $this->createService(
157 2
            $container,
158 2
            'factory.kernel',
159 2
            KernelFactory::class,
160
            [
161 2
                new Reference($this->buildContainerId('dispatcher.kernel_event')),
162 2
                '%'.$this->buildContainerId('kernel.path').'%',
163 2
                '%'.$this->buildContainerId('kernel.class').'%',
164 2
                '%'.$this->buildContainerId('kernel.env').'%',
165 2
                '%'.$this->buildContainerId('kernel.debug').'%'
166 2
            ]
167 2
        );
168 2
    }
169
170
    /**
171
     * {@inheritdoc}
172
     */
173 3
    public function process(ContainerBuilder $container)
174
    {
175 3
        $basePath = $container->getParameter('paths.base');
176 3
        $bootstrapPath = $container->getParameter($this->buildContainerId('kernel.bootstrap'));
177 3
        if ($bootstrapPath) {
178 2
            $bootstrapPathUnderBasePath = sprintf('%s/%s', $basePath, $bootstrapPath);
179 2
            if (file_exists($bootstrapPathUnderBasePath)) {
180 1
                $bootstrapPath = $bootstrapPathUnderBasePath;
181 1
            }
182 2
            if (file_exists($bootstrapPath)) {
183 1
                require_once($bootstrapPath);
184 1
            } else {
185 1
                throw new ProcessingException('Could not find bootstrap file !');
186
            }
187 1
        }
188
189
        // load kernel
190 2
        $kernelPath = $container->getParameter($this->buildContainerId('kernel.path'));
191 2
        $kernelPathUnderBasePath = sprintf('%s/%s', $basePath, $kernelPath);
192 2
        if (file_exists($kernelPathUnderBasePath)) {
193
            $kernelPath = $kernelPathUnderBasePath;
194
        }
195
196 2
        $container->getDefinition(self::KERNEL_SERVICE_ID)
197 2
            ->setFile($kernelPath);
198 2
    }
199
200
    /**
201
     * @param ContainerBuilder $container
202
     */
203 2
    protected function loadInitializer(ContainerBuilder $container)
204
    {
205 2
        $this->createService(
206 2
            $container,
207 2
            'initializer.kernel_aware',
208 2
            KernelAwareInitializer::class,
209 2
            [new Reference(self::KERNEL_SERVICE_ID)],
210 2
            ['context.initializer']
211 2
        );
212
213 2
        $this->createService(
214 2
            $container,
215 2
            'initializer.kernel_handler_aware',
216 2
            KernelHandlerAwareInitializer::class,
217 2
            [new Reference($this->buildContainerId('handler.kernel'))],
218 2
            ['context.initializer']
219 2
        );
220 2
    }
221
222
    /**
223
     * @param ContainerBuilder $container
224
     * @param $kernelConfig
225
     */
226 2
    protected function loadSubscriber(ContainerBuilder $container, $kernelConfig)
227
    {
228 2
        if (true === $kernelConfig['reboot']) {
229 1
            $this->createService(
230 1
                $container,
231 1
                'subscriber.reboot_kernel',
232 1
                RebootKernelSubscriber::class,
233 1
                [new Reference($this->buildContainerId('handler.kernel'))],
234 1
                [EventDispatcherExtension::SUBSCRIBER_TAG]
235 1
            );
236 1
        }
237 2
    }
238
239
    /**
240
     * @param ContainerBuilder $container
241
     * @param $kernelConfig
242
     */
243 2
    protected function loadContainerParameter(ContainerBuilder $container, $kernelConfig)
244
    {
245 2
        foreach ($kernelConfig as $key => $value) {
246 2
            $container->setParameter($this->buildContainerId(sprintf('kernel.%s', $key)), $value);
247 2
        }
248 2
    }
249
}
250