Passed
Push — master ( 513ae1...064a73 )
by Dominik
02:44
created

getOrmEmsConfigServiceProvider()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 68

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 34
CRAP Score 5.0133

Importance

Changes 0
Metric Value
dl 0
loc 68
ccs 34
cts 37
cp 0.9189
rs 8.387
c 0
b 0
f 0
cc 5
nc 1
nop 1
crap 5.0133

How to fix   Long Method   

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
declare(strict_types=1);
4
5
namespace Chubbyphp\ServiceProvider;
6
7
use Chubbyphp\ServiceProvider\Registry\DoctrineOrmManagerRegistry;
8
use Doctrine\Common\Cache\ApcuCache;
9
use Doctrine\Common\Cache\ArrayCache;
10
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain;
11
use Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver;
12
use Doctrine\DBAL\Types\Type;
13
use Doctrine\ORM\Cache\CacheConfiguration;
14
use Doctrine\ORM\Cache\DefaultCacheFactory;
15
use Doctrine\ORM\Cache\RegionsConfiguration;
16
use Doctrine\ORM\Configuration;
17
use Doctrine\ORM\EntityManager;
18
use Doctrine\ORM\EntityRepository;
19
use Doctrine\ORM\Mapping\ClassMetadataFactory;
20
use Doctrine\ORM\Mapping\DefaultEntityListenerResolver;
21
use Doctrine\ORM\Mapping\DefaultNamingStrategy;
22
use Doctrine\ORM\Mapping\DefaultQuoteStrategy;
23
use Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver;
24
use Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver;
25
use Doctrine\ORM\Mapping\Driver\XmlDriver;
26
use Doctrine\ORM\Mapping\Driver\YamlDriver;
27
use Doctrine\ORM\Repository\DefaultRepositoryFactory;
28
use Pimple\Container;
29
use Pimple\ServiceProviderInterface;
30
31
final class DoctrineOrmServiceProvider implements ServiceProviderInterface
32
{
33
    /**
34
     * Register ORM service.
35
     *
36
     * @param Container $container
37
     */
38 1
    public function register(Container $container)
39
    {
40 1
        $container['doctrine.orm.em'] = $this->getOrmEmDefinition($container);
41 1
        $container['doctrine.orm.em.cache_factory.apcu'] = $this->getOrmApcuCacheFactoryDefinition($container);
42 1
        $container['doctrine.orm.em.cache_factory.array'] = $this->getOrmArrayCacheFactoryDefinition($container);
43 1
        $container['doctrine.orm.em.config'] = $this->getOrmEmConfigDefinition($container);
44 1
        $container['doctrine.orm.em.default_options'] = $this->getOrmEmDefaultOptions();
45 1
        $container['doctrine.orm.ems'] = $this->getOrmEmsDefinition($container);
46 1
        $container['doctrine.orm.ems.config'] = $this->getOrmEmsConfigServiceProvider($container);
47 1
        $container['doctrine.orm.ems.options.initializer'] = $this->getOrmEmsOptionsInitializerDefinition($container);
48 1
        $container['doctrine.orm.entity.listener_resolver.default'] = $this->getOrmEntityListenerResolverDefinition($container);
49 1
        $container['doctrine.orm.manager_registry'] = $this->getOrmManagerRegistryDefintion($container);
50 1
        $container['doctrine.orm.mapping_driver.factory.annotation'] = $this->getOrmMappingDriverFactoryAnnotation($container);
51 1
        $container['doctrine.orm.mapping_driver.factory.php'] = $this->getOrmMappingDriverFactoryPhp($container);
52 1
        $container['doctrine.orm.mapping_driver.factory.simple_xml'] = $this->getOrmMappingDriverFactorySimpleXml($container);
53 1
        $container['doctrine.orm.mapping_driver.factory.simple_yml'] = $this->getOrmMappingDriverFactorySimpleYaml($container);
54 1
        $container['doctrine.orm.mapping_driver.factory.xml'] = $this->getOrmMappingDriverFactoryXml($container);
55 1
        $container['doctrine.orm.mapping_driver.factory.yml'] = $this->getOrmMappingDriverFactoryYaml($container);
56 1
        $container['doctrine.orm.mapping_driver_chain'] = $this->getOrmMappingDriverChainDefinition($container);
57 1
        $container['doctrine.orm.repository.factory.default'] = $this->getOrmRepositoryFactoryDefinition($container);
58 1
        $container['doctrine.orm.strategy.naming.default'] = $this->getOrmNamingStrategyDefinition($container);
59 1
        $container['doctrine.orm.strategy.quote.default'] = $this->getOrmQuoteStrategyDefinition($container);
60 1
    }
61
62
    /**
63
     * @param Container $container
64
     *
65
     * @return callable
66
     */
67
    private function getOrmEmDefinition(Container $container): callable
68
    {
69 1
        return function () use ($container) {
70 1
            $ems = $container['doctrine.orm.ems'];
71
72 1
            return $ems[$container['doctrine.orm.ems.default']];
73 1
        };
74
    }
75
76
    /**
77
     * @param Container $container
78
     *
79
     * @return callable
80
     */
81
    private function getOrmApcuCacheFactoryDefinition(Container $container): callable
82
    {
83 1
        return $container->factory(function () use ($container) {
84 1
            return new ApcuCache();
85 1
        });
86
    }
87
88
    /**
89
     * @param Container $container
90
     *
91
     * @return callable
92
     */
93
    private function getOrmArrayCacheFactoryDefinition(Container $container): callable
94
    {
95 1
        return $container->factory(function () use ($container) {
96 1
            return new ArrayCache();
97 1
        });
98
    }
99
100
    /**
101
     * @param Container $container
102
     *
103
     * @return callable
104
     */
105
    private function getOrmEmConfigDefinition(Container $container): callable
106
    {
107 1
        return function () use ($container) {
108 1
            $configs = $container['doctrine.orm.ems.config'];
109
110 1
            return $configs[$container['doctrine.orm.ems.default']];
111 1
        };
112
    }
113
114
    /**
115
     * @return array
116
     */
117 1
    private function getOrmEmDefaultOptions(): array
118
    {
119
        return [
120 1
            'cache.hydration' => 'array',
121 1
            'cache.metadata' => 'array',
122 1
            'cache.query' => 'array',
123 1
            'cache.second_level' => 'array',
124
            'class_metadata.factory.name' => ClassMetadataFactory::class,
125 1
            'connection' => 'default',
126
            'custom.datetime.functions' => [],
127
            'custom.hydration_modes' => [],
128
            'custom.numeric.functions' => [],
129
            'custom.string.functions' => [],
130 1
            'entity.listener_resolver' => 'default',
131
            'mappings' => [],
132
            'proxies.auto_generate' => true,
133 1
            'proxies.dir' => sys_get_temp_dir().'/doctrine/orm/proxies',
134 1
            'proxies.namespace' => 'DoctrineProxy',
135
            'query_hints' => [],
136
            'repository.default.class' => EntityRepository::class,
137 1
            'repository.factory' => 'default',
138 1
            'strategy.naming' => 'default',
139 1
            'strategy.quote' => 'default',
140
            'types' => [],
141
        ];
142
    }
143
144
    /**
145
     * @param Container $container
146
     *
147
     * @return callable
148
     */
149
    private function getOrmEmsDefinition(Container $container): callable
150
    {
151 1
        return function () use ($container) {
152 1
            $container['doctrine.orm.ems.options.initializer']();
153
154 1
            $ems = new Container();
155 1
            foreach ($container['doctrine.orm.ems.options'] as $name => $options) {
156 1
                if ($container['doctrine.orm.ems.default'] === $name) {
157
                    // we use shortcuts here in case the default has been overridden
158 1
                    $config = $container['doctrine.orm.em.config'];
159
                } else {
160
                    $config = $container['doctrine.orm.ems.config'][$name];
161
                }
162
163 1
                $ems[$name] = function () use ($container, $options, $config) {
164 1
                    return EntityManager::create(
165 1
                        $container['doctrine.dbal.dbs'][$options['connection']],
166 1
                        $config,
167 1
                        $container['doctrine.dbal.dbs.event_manager'][$options['connection']]
168
                    );
169 1
                };
170
            }
171
172 1
            return $ems;
173 1
        };
174
    }
175
176
    /**
177
     * @param Container $container
178
     *
179
     * @return callable
180
     */
181
    private function getOrmEmsConfigServiceProvider(Container $container): callable
182
    {
183 1
        return function () use ($container) {
184 1
            $container['doctrine.orm.ems.options.initializer']();
185
186 1
            $configs = new Container();
187 1
            foreach ($container['doctrine.orm.ems.options'] as $name => $options) {
188 1
                $config = new Configuration();
189
190 1
                $config->setSQLLogger($container['doctrine.dbal.dbs.config'][$name]->getSQLLogger());
191
192 1
                foreach (['query', 'hydration', 'metadata'] as $cacheType) {
193 1
                    $this->assignCache($container, $config, $options, $cacheType);
194
                }
195
196 1
                $config->setResultCacheImpl($container['doctrine.dbal.dbs.config'][$name]->getResultCacheImpl());
197
198 1
                $config->setClassMetadataFactoryName($options['class_metadata.factory.name']);
199
200 1
                $config->setCustomDatetimeFunctions($options['custom.datetime.functions']);
201 1
                $config->setCustomHydrationModes($options['custom.hydration_modes']);
202 1
                $config->setCustomNumericFunctions($options['custom.numeric.functions']);
203 1
                $config->setCustomStringFunctions($options['custom.string.functions']);
204
205 1
                $config->setEntityListenerResolver(
206
                    $container[
207 1
                        sprintf('doctrine.orm.entity.listener_resolver.%s', $options['entity.listener_resolver'])
208
                    ]
209
                );
210
211 1
                $config->setMetadataDriverImpl(
212 1
                    $container['doctrine.orm.mapping_driver_chain']($name, $config, (array) $options['mappings'])
213
                );
214
215 1
                $config->setAutoGenerateProxyClasses($options['proxies.auto_generate']);
216 1
                $config->setProxyDir($options['proxies.dir']);
217 1
                $config->setProxyNamespace($options['proxies.namespace']);
218
219 1
                $config->setDefaultQueryHints($options['query_hints']);
220
221 1
                $config->setRepositoryFactory(
222 1
                    $container[sprintf('doctrine.orm.repository.factory.%s', $options['repository.factory'])]
223
                );
224 1
                $config->setDefaultRepositoryClassName($options['repository.default.class']);
225
226 1
                $this->assignSecondLevelCache($container, $config, $options);
227
228 1
                $config->setNamingStrategy(
229 1
                    $container[sprintf('doctrine.orm.strategy.naming.%s', $options['strategy.naming'])]
230
                );
231 1
                $config->setQuoteStrategy(
232 1
                    $container[sprintf('doctrine.orm.strategy.quote.%s', $options['strategy.quote'])]
233
                );
234
235 1
                foreach ((array) $options['types'] as $typeName => $typeClass) {
236
                    if (Type::hasType($typeName)) {
237
                        Type::overrideType($typeName, $typeClass);
238
                    } else {
239
                        Type::addType($typeName, $typeClass);
240
                    }
241
                }
242
243 1
                $configs[$name] = $config;
244
            }
245
246 1
            return $configs;
247 1
        };
248
    }
249
250
    /**
251
     * @param Container     $container
252
     * @param Configuration $config
253
     * @param array         $options
254
     * @param string        $cacheType
255
     */
256 1
    private function assignCache(Container $container, Configuration $config, array $options, string $cacheType)
257
    {
258 1
        $optionsKey = sprintf('cache.%s', $cacheType);
259
260 1
        $cacheFactoryKey = sprintf('doctrine.orm.em.cache_factory.%s', $options[$optionsKey]);
261 1
        $setMethod = sprintf('set%sCacheImpl', ucfirst($cacheType));
262
263 1
        $config->$setMethod($container[$cacheFactoryKey]);
264 1
    }
265
266
    /**
267
     * @param Container     $container
268
     * @param Configuration $config
269
     * @param array         $options
270
     */
271 1
    private function assignSecondLevelCache(Container $container, Configuration $config, array $options)
272
    {
273 1
        $cacheFactoryKey = sprintf('doctrine.orm.em.cache_factory.%s', $options['cache.second_level']);
274 1
        $secondLevelCacheAdapter = $container[$cacheFactoryKey];
275
276 1
        $regionsCacheConfiguration = new RegionsConfiguration();
277 1
        $factory = new DefaultCacheFactory($regionsCacheConfiguration, $secondLevelCacheAdapter);
278
279 1
        $cacheConfiguration = new CacheConfiguration();
280 1
        $cacheConfiguration->setCacheFactory($factory);
281 1
        $cacheConfiguration->setRegionsConfiguration($regionsCacheConfiguration);
282
283 1
        $config->setSecondLevelCacheEnabled(true);
284 1
        $config->setSecondLevelCacheConfiguration($cacheConfiguration);
285 1
    }
286
287
    /**
288
     * @param Container $container
289
     *
290
     * @return callable
291
     */
292 View Code Duplication
    private function getOrmEmsOptionsInitializerDefinition(Container $container): callable
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...
293
    {
294 1
        return $container->protect(function () use ($container) {
295 1
            static $initialized = false;
296
297 1
            if ($initialized) {
298 1
                return;
299
            }
300
301 1
            $initialized = true;
302
303 1
            if (!isset($container['doctrine.orm.ems.options'])) {
304 1
                $container['doctrine.orm.ems.options'] = [
305 1
                    'default' => isset($container['doctrine.orm.em.options'])
306
                        ? $container['doctrine.orm.em.options'] : [],
307
                ];
308
            }
309
310 1
            $tmp = $container['doctrine.orm.ems.options'];
311 1
            foreach ($tmp as $name => &$options) {
312 1
                $options = array_replace($container['doctrine.orm.em.default_options'], $options);
313
314 1
                if (!isset($container['doctrine.orm.ems.default'])) {
315 1
                    $container['doctrine.orm.ems.default'] = $name;
316
                }
317
            }
318
319 1
            $container['doctrine.orm.ems.options'] = $tmp;
320 1
        });
321
    }
322
323
    /**
324
     * @param Container $container
325
     *
326
     * @return callable
327
     */
328
    private function getOrmEntityListenerResolverDefinition(Container $container): callable
329
    {
330 1
        return function () use ($container) {
331 1
            return new DefaultEntityListenerResolver();
332 1
        };
333
    }
334
335
    /**
336
     * @param Container $container
337
     *
338
     * @return callable
339
     */
340
    private function getOrmManagerRegistryDefintion(Container $container): callable
0 ignored issues
show
Unused Code introduced by
The parameter $container is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
341
    {
342 1
        return function ($container) {
343 1
            return new DoctrineOrmManagerRegistry($container);
344 1
        };
345
    }
346
347
    /**
348
     * @param Container $container
349
     *
350
     * @return callable
351
     */
352
    private function getOrmMappingDriverFactoryAnnotation(Container $container): callable
353
    {
354 1
        return $container->protect(function (array $mapping, Configuration $config) {
355
            return $config->newDefaultAnnotationDriver((array) $mapping['path'], $false);
0 ignored issues
show
Bug introduced by
The variable $false does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
356 1
        });
357
    }
358
359
    /**
360
     * @param Container $container
361
     *
362
     * @return callable
363
     */
364
    private function getOrmMappingDriverFactoryPhp(Container $container): callable
365
    {
366 1
        return $container->protect(function (array $mapping, Configuration $config) {
0 ignored issues
show
Unused Code introduced by
The parameter $config is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
367
            return new StaticPHPDriver($mapping['path']);
368 1
        });
369
    }
370
371
    /**
372
     * @param Container $container
373
     *
374
     * @return callable
375
     */
376 View Code Duplication
    private function getOrmMappingDriverFactorySimpleYaml(Container $container): callable
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...
377
    {
378 1
        return $container->protect(function (array $mapping, Configuration $config) {
0 ignored issues
show
Unused Code introduced by
The parameter $config is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
379
            return new SimplifiedYamlDriver(
380
                [$mapping['path'] => $mapping['namespace']],
381
                $mapping['extension'] ?? SimplifiedYamlDriver::DEFAULT_FILE_EXTENSION
382
            );
383 1
        });
384
    }
385
386
    /**
387
     * @param Container $container
388
     *
389
     * @return callable
390
     */
391 View Code Duplication
    private function getOrmMappingDriverFactorySimpleXml(Container $container): callable
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...
392
    {
393 1
        return $container->protect(function (array $mapping, Configuration $config) {
0 ignored issues
show
Unused Code introduced by
The parameter $config is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
394
            return new SimplifiedXmlDriver(
395
                [$mapping['path'] => $mapping['namespace']],
396
                $mapping['extension'] ?? SimplifiedXmlDriver::DEFAULT_FILE_EXTENSION
397
            );
398 1
        });
399
    }
400
401
    /**
402
     * @param Container $container
403
     *
404
     * @return callable
405
     */
406
    private function getOrmMappingDriverFactoryYaml(Container $container): callable
407
    {
408 1
        return $container->protect(function (array $mapping, Configuration $config) {
0 ignored issues
show
Unused Code introduced by
The parameter $config is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
409
            return new YamlDriver($mapping['path'], $mapping['extension'] ?? YamlDriver::DEFAULT_FILE_EXTENSION);
410 1
        });
411
    }
412
413
    /**
414
     * @param Container $container
415
     *
416
     * @return callable
417
     */
418
    private function getOrmMappingDriverFactoryXml(Container $container): callable
419
    {
420 1
        return $container->protect(function (array $mapping, Configuration $config) {
0 ignored issues
show
Unused Code introduced by
The parameter $config is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
421
            return new XmlDriver($mapping['path'], $mapping['extension'] ?? XmlDriver::DEFAULT_FILE_EXTENSION);
422 1
        });
423
    }
424
425
    /**
426
     * @param Container $container
427
     *
428
     * @return callable
429
     */
430
    private function getOrmMappingDriverChainDefinition(Container $container): callable
431
    {
432 1
        return $container->protect(function (string $name, Configuration $config, array $mappings) use ($container) {
433 1
            $chain = new MappingDriverChain();
434 1
            foreach ($mappings as $mapping) {
435
                if (!is_array($mapping)) {
436
                    throw new \InvalidArgumentException(
437
                        'The "doctrine.orm.em.options" option "mappings" should be an array of arrays.'
438
                    );
439
                }
440
441
                if (isset($mapping['alias'])) {
442
                    $config->addEntityNamespace($mapping['alias'], $mapping['namespace']);
443
                }
444
445
                $factoryKey = sprintf('doctrine.orm.mapping_driver.factory.%s', $mapping['type']);
446
447
                $chain->addDriver($container[$factoryKey]($mapping, $config), $mapping['namespace']);
448
            }
449
450 1
            return $chain;
451 1
        });
452
    }
453
454
    /**
455
     * @param Container $container
456
     *
457
     * @return callable
458
     */
459
    private function getOrmRepositoryFactoryDefinition(Container $container): callable
460
    {
461 1
        return function () use ($container) {
462 1
            return new DefaultRepositoryFactory();
463 1
        };
464
    }
465
466
    /**
467
     * @param Container $container
468
     *
469
     * @return callable
470
     */
471
    private function getOrmNamingStrategyDefinition(Container $container): callable
472
    {
473 1
        return function () use ($container) {
474 1
            return new DefaultNamingStrategy();
475 1
        };
476
    }
477
478
    /**
479
     * @param Container $container
480
     *
481
     * @return callable
482
     */
483
    private function getOrmQuoteStrategyDefinition(Container $container): callable
484
    {
485 1
        return function () use ($container) {
486 1
            return new DefaultQuoteStrategy();
487 1
        };
488
    }
489
}
490