Failed Conditions
Push — feature/stepLogger ( ec1117...9face9 )
by Yo
04:15
created

checkUtilsExtensionAlreadyLoaded()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
crap 6
1
<?php
2
namespace Yoanm\Behat3SymfonyExtension\ServiceContainer;
3
4
use Behat\MinkExtension\ServiceContainer\MinkExtension;
5
use Behat\Testwork\ServiceContainer\Extension;
6
use Behat\Testwork\ServiceContainer\ExtensionManager;
7
use Monolog\Logger;
8
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
9
use Symfony\Component\Config\FileLocator;
10
use Symfony\Component\DependencyInjection\ContainerBuilder;
11
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
12
use Yoanm\Behat3SymfonyExtension\ServiceContainer\Configuration\KernelConfiguration;
13
use Yoanm\Behat3SymfonyExtension\ServiceContainer\Configuration\LoggerConfiguration;
14
use Yoanm\Behat3SymfonyExtension\ServiceContainer\DriverFactory\Behat3SymfonyFactory;
15
use Yoanm\BehatUtilsExtension\ServiceContainer\BehatUtilsExtension;
16
17
class Behat3SymfonyExtension implements Extension
18
{
19
    const TEST_CLIENT_SERVICE_ID = 'behat3_symfony_extension.test.client';
20
    const KERNEL_SERVICE_ID = 'behat3_symfony_extension.kernel';
21
22
    /**
23
     * {@inheritdoc}
24
     */
25 1
    public function getConfigKey()
26
    {
27 1
        return 'behat3_symfony';
28
    }
29
30
    // @codeCoverageIgnoreStart
31
    /**
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
    /**
46
     * {@inheritdoc}
47
     */
48
    public function configure(ArrayNodeDefinition $builder)
49
    {
50
        $castToBool = function ($value) {
51
            $filtered = filter_var(
52
                $value,
53
                FILTER_VALIDATE_BOOLEAN,
54
                FILTER_NULL_ON_FAILURE
55
            );
56
57
            return (null === $filtered) ? (bool) $value : $filtered;
58
        };
59
        $builder->children()
60
            ->booleanNode('debug_mode')
61
                ->beforeNormalization()
62
                ->always()
63
                    ->then($castToBool)
64
                ->end()
65
                ->defaultFalse()
66
            ->end()
67
            ->end();
68
        $builder->append((new KernelConfiguration())->getConfigTreeBuilder());
69
        $builder->append((new LoggerConfiguration())->getConfigTreeBuilder());
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function load(ContainerBuilder $container, array $config)
76
    {
77
        $config = $this->normalizeConfig($config);
78
        $this->bindConfigToContainer($container, $config);
79
80
        $loader = new XmlFileLoader(
81
            $container,
82
            new FileLocator(__DIR__.'/../Resources/config')
83
        );
84
85
        $loader->load('client.xml');
86
        $loader->load('kernel.xml');
87
        $loader->load('initializer.xml');
88
        if (true === $config['kernel']['reboot']) {
89
            $loader->load('kernel_auto_reboot.xml');
90
        }
91
        if (true === $config['kernel']['debug']) {
92
            $loader->load('kernel_debug_mode.xml');
93
94
            // Override log level parameter
95
            $this->checkUtilsExtensionAlreadyLoaded($container);
96
            $container->setParameter('behat_utils_extension.logger.level', Logger::DEBUG);
97
        }
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103 3
    public function process(ContainerBuilder $container)
104
    {
105 3
        $bootstrapPath = $container->getParameter('behat3_symfony_extension.kernel.bootstrap');
106 3
        if ($bootstrapPath) {
107 2
            require_once($this->normalizePath($container, $bootstrapPath));
108 2
        }
109
110
        // load kernel
111 3
        $container->getDefinition(self::KERNEL_SERVICE_ID)
112 3
            ->setFile(
113 3
                $this->normalizePath(
114 3
                    $container,
115 3
                    $container->getParameter('behat3_symfony_extension.kernel.path')
116 3
                )
117 3
            );
118 3
    }
119
120
    /**
121
     * @param ContainerBuilder $container
122
     * @param string           $path
123
     *
124
     * @return string
125
     */
126 3
    protected function normalizePath(ContainerBuilder $container, $path)
127
    {
128 3
        $basePath = $container->getParameter('paths.base');
129 3
        $pathUnderBasePath = sprintf('%s/%s', $basePath, $path);
130 3
        if (file_exists($pathUnderBasePath)) {
131 2
            $path = $pathUnderBasePath;
132 2
        }
133
134 3
        return $path;
135
    }
136
137
    /**
138
     * @param ContainerBuilder $container
139
     * @param array            $config
140
     * @param string           $baseId
141
     */
142
    protected function bindConfigToContainer(
143
        ContainerBuilder $container,
144
        array $config,
145
        $baseId = 'behat3_symfony_extension'
146
    ) {
147
        foreach ($config as $configKey => $configValue) {
148
            if (is_array($configValue)) {
149
                $this->bindConfigToContainer(
150
                    $container,
151
                    $configValue,
152
                    sprintf('%s.%s', $baseId, $configKey)
153
                );
154
            } else {
155
                $container->setParameter(sprintf('%s.%s', $baseId, $configKey), $configValue);
156
            }
157
        }
158
    }
159
160
    /**
161
     * @param array $config
162
     * @return array
163
     */
164
    protected function normalizeConfig(array $config)
165
    {
166
        if (true === $config['debug_mode']) {
167
            $config['kernel']['debug'] = true;
168
        }
169
170
        return $config;
171
    }
172
173
    /**
174
     * @param ContainerBuilder $container
175
     * @throws \Exception
176
     */
177
    protected function checkUtilsExtensionAlreadyLoaded(ContainerBuilder $container)
178
    {
179
        if (!$container->hasParameter('behat_utils_extension.logger.path')) {
180
            throw new \Exception('BehatUtilsExtension must be loaded before this one !');
181
        }
182
    }
183
}
184