Completed
Pull Request — master (#141)
by Evgenij
01:47
created

configureDoctrineMigrationsCheck()   D

Complexity

Conditions 15
Paths 197

Size

Total Lines 91
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 91
rs 4.597
c 0
b 0
f 0
cc 15
eloc 51
nc 197
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Liip\MonitorBundle\DependencyInjection;
4
5
use Doctrine\DBAL\Connection;
6
use Doctrine\DBAL\Driver\PDOSqlite\Driver;
7
use Doctrine\DBAL\Migrations\Configuration\AbstractFileConfiguration;
8
use Doctrine\DBAL\Migrations\Configuration\Configuration as MigrationConfiguration;
9
use Symfony\Component\Config\FileLocator;
10
use Symfony\Component\DependencyInjection\ContainerBuilder;
11
use Symfony\Component\DependencyInjection\DefinitionDecorator;
12
use Symfony\Component\DependencyInjection\Loader;
13
use Symfony\Component\DependencyInjection\Reference;
14
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
15
16
class LiipMonitorExtension extends Extension
17
{
18
    /**
19
     * Loads the services based on your application configuration.
20
     *
21
     * @param array            $configs
22
     * @param ContainerBuilder $container
23
     */
24
    public function load(array $configs, ContainerBuilder $container)
25
    {
26
        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
27
        $loader->load('runner.xml');
28
        $loader->load('helper.xml');
29
30
        $configuration = new Configuration();
31
        $config = $this->processConfiguration($configuration, $configs);
32
33
        if (null === $config['view_template']) {
34
            $config['view_template'] = __DIR__.'/../Resources/views/health/index.html.php';
35
        }
36
37
        if ($config['enable_controller']) {
38
            $container->setParameter(sprintf('%s.view_template', $this->getAlias()), $config['view_template']);
39
            $loader->load('controller.xml');
40
        }
41
42
        if ($config['mailer']['enabled']) {
43
            $loader->load('helper/swift_mailer.xml');
44
45
            foreach ($config['mailer'] as $key => $value) {
46
                $container->setParameter(sprintf('%s.mailer.%s', $this->getAlias(), $key), $value);
47
            }
48
        }
49
50
        $container->setParameter(sprintf('%s.default_group', $this->getAlias()), $config['default_group']);
51
52
        if (empty($config['checks'])) {
53
            return;
54
        }
55
56
        $checksLoaded = array();
57
        $containerParams = array();
58
        foreach ($config['checks']['groups'] as $group => $checks) {
59
            if (empty($checks)) {
60
                continue;
61
            }
62
63
            foreach ($checks as $check => $values) {
64
                if (empty($values)) {
65
                    continue;
66
                }
67
68
                $containerParams['groups'][$group][$check] = $values;
69
                $this->setParameters($container, $check, $group, $values);
70
71
                if (!in_array($check, $checksLoaded)) {
72
                    $loader->load('checks/'.$check.'.xml');
73
                    $checksLoaded[] = $check;
74
                }
75
            }
76
        }
77
78
        $container->setParameter(sprintf('%s.checks', $this->getAlias()), $containerParams);
79
        $this->configureDoctrineMigrationsCheck($container, $containerParams);
80
    }
81
82
    /**
83
     * @param ContainerBuilder $container
84
     * @param string           $checkName
85
     * @param string           $group
86
     * @param array            $values
87
     */
88
    private function setParameters(ContainerBuilder $container, $checkName, $group, $values)
89
    {
90
        $prefix = sprintf('%s.check.%s', $this->getAlias(), $checkName);
91
        switch ($checkName) {
92
            case 'class_exists':
93
            case 'cpu_performance':
94
            case 'php_extensions':
95
            case 'php_version':
96
            case 'php_flags':
97
            case 'readable_directory':
98
            case 'writable_directory':
99
            case 'process_running':
100
            case 'doctrine_dbal':
101
            case 'http_service':
102
            case 'guzzle_http_service':
103
            case 'memcache':
104
            case 'redis':
105
            case 'rabbit_mq':
106
            case 'stream_wrapper_exists':
107
            case 'file_ini':
108
            case 'file_json':
109
            case 'file_xml':
110
            case 'file_yaml':
111
            case 'expressions':
112
                $container->setParameter($prefix.'.'.$group, $values);
113
                continue;
114
115
            case 'symfony_version':
116
                continue;
117
118
            case 'opcache_memory':
119
                if (!class_exists('ZendDiagnostics\Check\OpCacheMemory')) {
120
                    throw new \InvalidArgumentException('Please require at least "v1.0.4" of "ZendDiagnostics"');
121
                }
122
                continue;
123
124
            case 'doctrine_migrations':
125
                if (!class_exists('ZendDiagnostics\Check\DoctrineMigration')) {
126
                    throw new \InvalidArgumentException('Please require at least "v1.0.6" of "ZendDiagnostics"');
127
                }
128
129
                if (!class_exists('Doctrine\Bundle\MigrationsBundle\Command\DoctrineCommand')) {
130
                    throw new \InvalidArgumentException('Please require at least "v1.0.0" of "DoctrineMigrationsBundle"');
131
                }
132
133
                if (!class_exists('Doctrine\DBAL\Migrations\Configuration\Configuration')) {
134
                    throw new \InvalidArgumentException('Please require at least "v1.1.0" of "Doctrine Migrations Library"');
135
                }
136
137
                $container->setParameter($prefix.'.'.$group, $values);
138
                continue;
139
140
            case 'pdo_connections':
141
                if (!class_exists('ZendDiagnostics\Check\PDOCheck')) {
142
                    throw new \InvalidArgumentException('Please require at least "v1.0.5" of "ZendDiagnostics"');
143
                }
144
                $container->setParameter($prefix.'.'.$group, $values);
145
                continue;
146
147
        }
148
149
        if (is_array($values)) {
150
            foreach ($values as $key => $value) {
151
                $container->setParameter($prefix.'.'.$key.'.'.$group, $value);
152
            }
153
        }
154
    }
155
156
    /**
157
     * Set up doctrine migration configuration services
158
     *
159
     * @param ContainerBuilder $container The container
160
     * @param array            $params    Container params
161
     *
162
     * @return void
163
     */
164
    private function configureDoctrineMigrationsCheck(ContainerBuilder $container, array $params)
165
    {
166
        if (!$container->hasDefinition('liip_monitor.check.doctrine_migrations') || !isset($params['groups'])) {
167
            return;
168
        }
169
170
        // -------
171
        // This part must be in sync with Doctrine\DBAL\Migrations\Tools\Console\Helper\ConfigurationHelper::loadConfig
172
        $map = array(
173
            'xml'   => '\XmlConfiguration',
174
            'yaml'  => '\YamlConfiguration',
175
            'yml'   => '\YamlConfiguration',
176
            'php'   => '\ArrayConfiguration',
177
            'json'  => '\JsonConfiguration'
178
        );
179
        // --------
180
181
        foreach ($params['groups'] as $groupName => $groupChecks) {
182
            if (!isset($groupChecks['doctrine_migrations'])) {
183
                continue;
184
            }
185
186
            $services = [];
187
            foreach ($groupChecks['doctrine_migrations'] as $key => $config) {
188
                $filename = $container->getParameterBag()->resolveValue($config['configuration_file']);
189
                $info     = pathinfo($filename);
190
                // check we can support this file type
191
                if (empty($map[$info['extension']])) {
192
                    throw new \InvalidArgumentException('Given config file type is not supported');
193
                }
194
195
                $class  = 'Doctrine\DBAL\Migrations\Configuration';
196
                $class .= $map[$info['extension']];
197
                // -------
198
199
                /** @var AbstractFileConfiguration $configuration */
200
                $connection    = new Connection([], new Driver());
201
                $configuration = new $class($connection); // needed for correct migration loading
202
                $configuration->load($filename);
203
204
                $serviceConfiguration =
205
                    new DefinitionDecorator('liip_monitor.check.doctrine_migrations.abstract_configuration');
206
                $serviceConfiguration->replaceArgument(
207
                    0,
208
                    new Reference(sprintf('doctrine.dbal.%s_connection', $config['connection']))
209
                );
210
211
                if ($configuration->getMigrationsNamespace()) {
212
                    $serviceConfiguration->addMethodCall('setMigrationsNamespace', [$configuration->getMigrationsNamespace()]);
213
                }
214
215
                if ($configuration->getMigrationsTableName()) {
216
                    $serviceConfiguration->addMethodCall('setMigrationsTableName', [$configuration->getMigrationsTableName()]);
217
                }
218
219
                if ($configuration->getMigrationsColumnName()) {
220
                    $serviceConfiguration->addMethodCall('setMigrationsColumnName', [$configuration->getMigrationsColumnName()]);
221
                }
222
223
                if ($configuration->getName()) {
224
                    $serviceConfiguration->addMethodCall('setName', [$configuration->getName()]);
225
                }
226
227
                if ($configuration->getMigrationsDirectory()) {
228
                    $serviceConfiguration->addMethodCall('setMigrationsDirectory', [$configuration->getMigrationsDirectory()]);
229
                }
230
231
                /** @var AbstractFileConfiguration $diff */
232
                $versions = $this->getPredefinedMigrations($configuration, $connection);
233
                if ($versions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $versions of type array[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
234
                    $serviceConfiguration->addMethodCall('registerMigrations', [$versions]);
235
                }
236
237
                $serviceConfiguration->addMethodCall('configure', []);
238
239
                if ($configuration->areMigrationsOrganizedByYear()) {
240
                    $serviceConfiguration->addMethodCall('setMigrationsAreOrganizedByYear', [true]);
241
                } elseif ($configuration->areMigrationsOrganizedByYearAndMonth()) {
242
                    $serviceConfiguration->addMethodCall('setMigrationsAreOrganizedByYearAndMonth', [true]);
243
                }
244
245
                $serviceId = sprintf('liip_monitor.check.doctrine_migrations.configuration.%s.%s', $groupName, $key);
246
                $container->setDefinition($serviceId, $serviceConfiguration);
247
248
                $services[$key] = $serviceId;
249
            }
250
251
            $parameter = sprintf('%s.check.%s.%s', $this->getAlias(), 'doctrine_migrations', $groupName);
252
            $container->setParameter($parameter, $services);
253
        }
254
    }
255
256
    /**
257
     * Return key-value array with migration version as key and class as a value defined in config file
258
     *
259
     * @param AbstractFileConfiguration $config Current configuration
260
     * @param Connection                $connection Fake connections
261
     *
262
     * @return array[]
263
     */
264
    private function getPredefinedMigrations(AbstractFileConfiguration $config, Connection $connection)
265
    {
266
        $result = array();
267
268
        $diff = new MigrationConfiguration($connection);
269
        $diff->setMigrationsNamespace($config->getMigrationsNamespace());
270
        $diff->setMigrationsDirectory($config->getMigrationsDirectory());
271
        foreach ($config->getMigrations() as $version) {
272
            $result[$version->getVersion()] = get_class($version->getMigration());
273
        }
274
275
        foreach ($diff->getAvailableVersions() as $version) {
276
            unset($result[$version]);
277
        }
278
279
        return $result;
280
    }
281
}
282