Failed Conditions
Pull Request — master (#16)
by Yo
05:10 queued 02:54
created

KernelSubExtension::process()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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