Passed
Push — master ( bed458...b2aa02 )
by Dominik
02:46
created

getOrmEmConfigByNameAndOptionsDefinition()   B

Complexity

Conditions 7
Paths 1

Size

Total Lines 65
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 7.5853

Importance

Changes 0
Metric Value
dl 0
loc 65
ccs 27
cts 35
cp 0.7714
rs 7.1439
c 0
b 0
f 0
cc 7
eloc 40
nc 1
nop 3
crap 7.5853

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
/*
6
 * (c) Beau Simensen <[email protected]> (https://github.com/dflydev/dflydev-doctrine-orm-service-provider)
7
 */
8
9
namespace Chubbyphp\ServiceProvider;
10
11
use Doctrine\Common\Cache\ApcuCache;
12
use Doctrine\Common\Cache\ArrayCache;
13
use Doctrine\Common\Cache\CacheProvider;
14
use Doctrine\Common\Cache\FilesystemCache;
15
use Doctrine\Common\Cache\MemcacheCache;
16
use Doctrine\Common\Cache\MemcachedCache;
17
use Doctrine\Common\Cache\XcacheCache;
18
use Doctrine\Common\Cache\RedisCache;
19
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain;
20
use Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver;
21
use Doctrine\DBAL\Types\Type;
22
use Doctrine\ORM\Configuration;
23
use Doctrine\ORM\EntityManager;
24
use Doctrine\ORM\EntityRepository;
25
use Doctrine\ORM\Mapping\ClassMetadataFactory;
26
use Doctrine\ORM\Mapping\DefaultEntityListenerResolver;
27
use Doctrine\ORM\Mapping\DefaultNamingStrategy;
28
use Doctrine\ORM\Mapping\DefaultQuoteStrategy;
29
use Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver;
30
use Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver;
31
use Doctrine\ORM\Mapping\Driver\XmlDriver;
32
use Doctrine\ORM\Mapping\Driver\YamlDriver;
33
use Doctrine\ORM\Repository\DefaultRepositoryFactory;
34
use Pimple\Container;
35
use Pimple\ServiceProviderInterface;
36
37
final class DoctrineOrmServiceProvider implements ServiceProviderInterface
38
{
39
    /**
40
     * Register ORM service.
41
     *
42
     * @param Container $container
43
     */
44 2
    public function register(Container $container)
45
    {
46 2
        $container['orm.em.default_options'] = $this->getOrmEmDefaultOptions();
47 2
        $container['orm.ems.options.initializer'] = $this->getOrmEmsOptionsInitializerDefinition($container);
48 2
        $container['orm.ems'] = $this->getOrmEmsDefinition($container);
49 2
        $container['orm.ems.config'] = $this->getOrmEmsConfigServiceProvider($container);
50 2
        $container['orm.cache.configurer'] = $this->getOrmCacheConfigurerDefinition($container);
51 2
        $container['orm.cache.locator'] = $this->getOrmCacheLocatorDefinition($container);
52 2
        $container['orm.cache.factory'] = $this->getOrmCacheFactoryDefinition($container);
53 2
        $container['orm.cache.factory.apcu'] = $this->getOrmCacheFactoryApcuDefinition($container);
54 2
        $container['orm.cache.factory.array'] = $this->getOrmCacheFactoryArrayDefinition($container);
55 2
        $container['orm.cache.factory.filesystem'] = $this->getOrmCacheFactoryFilesystemDefinition($container);
56 2
        $container['orm.cache.factory.memcache'] = $this->getOrmCacheFactoryMemcacheDefinition($container);
57 2
        $container['orm.cache.factory.memcached'] = $this->getOrmCacheFactoryMemcachedDefinition($container);
58 2
        $container['orm.cache.factory.redis'] = $this->getOrmCacheFactoryRedisDefinition($container);
59 2
        $container['orm.cache.factory.xcache'] = $this->getOrmCacheFactoryXCacheDefinition($container);
60 2
        $container['orm.default_cache'] = ['driver' => 'array'];
61 2
        $container['orm.proxies_dir'] = sys_get_temp_dir();
62 2
        $container['orm.proxies_namespace'] = 'DoctrineProxy';
63 2
        $container['orm.auto_generate_proxies'] = true;
64 2
        $container['orm.custom.functions.string'] = [];
65 2
        $container['orm.custom.functions.numeric'] = [];
66 2
        $container['orm.custom.functions.datetime'] = [];
67 2
        $container['orm.custom.hydration_modes'] = [];
68 2
        $container['orm.class_metadata_factory_name'] = ClassMetadataFactory::class;
69 2
        $container['orm.default_repository_class'] = EntityRepository::class;
70 2
        $container['orm.entity_listener_resolver'] = $this->getOrmEntityListenerResolverDefinition($container);
71 2
        $container['orm.repository_factory'] = $this->getOrmRepositoryFactoryDefinition($container);
72 2
        $container['orm.strategy.naming'] = $this->getOrmNamingStrategyDefinition($container);
73 2
        $container['orm.strategy.quote'] = $this->getOrmQuoteStrategyDefinition($container);
74 2
        $container['orm.mapping_driver_chain.locator'] = $this->getOrmMappingDriverChainLocatorDefinition($container);
75 2
        $container['orm.mapping_driver_chain.factory'] = $this->getOrmMappingDriverChainFactoryDefinition($container);
76 2
        $container['orm.em'] = $this->getOrmEmDefinition($container);
77 2
        $container['orm.em.config'] = $this->getOrmEmConfigDefinition($container);
78
79 2
        $container['orm.mapping_driver.factory.annotation'] = $container->protect(function (array $entity, Configuration $config) {
80 1
            $useSimpleAnnotationReader = $entity['use_simple_annotation_reader'] ?? true;
81
82 1
            return $config->newDefaultAnnotationDriver(
83 1
                (array) $entity['path'],
84 1
                $useSimpleAnnotationReader
85
            );
86 2
        });
87
88 2
        $container['orm.mapping_driver.factory.yml'] = $container->protect(function (array $entity) {
89 1
            return new YamlDriver($entity['path']);
90 2
        });
91
92 2
        $container['orm.mapping_driver.factory.simple_yml'] = $container->protect(function (array $entity) {
93 1
            return new SimplifiedYamlDriver([$entity['path'] => $entity['namespace']]);
94 2
        });
95
96 2
        $container['orm.mapping_driver.factory.xml'] = $container->protect(function (array $entity) {
97 1
            return new XmlDriver($entity['path']);
98 2
        });
99
100 2
        $container['orm.mapping_driver.factory.simple_xml'] = $container->protect(function (array $entity) {
101 1
            return new SimplifiedXmlDriver([$entity['path'] => $entity['namespace']]);
102 2
        });
103
104 2
        $container['orm.mapping_driver.factory.php'] = $container->protect(function (array $entity) {
105 1
            return new StaticPHPDriver($entity['path']);
106 2
        });
107 2
    }
108
109
    /**
110
     * @return array
111
     */
112 2
    private function getOrmEmDefaultOptions(): array
113
    {
114
        return [
115 2
            'connection' => 'default',
116
            'mappings' => [],
117
            'types' => [],
118
        ];
119
    }
120
121
    /**
122
     * @param Container $container
123
     *
124
     * @return \Closure
125
     */
126
    private function getOrmEmsOptionsInitializerDefinition(Container $container): \Closure
127
    {
128 2
        return $container->protect(function () use ($container) {
129 2
            static $initialized = false;
130
131 2
            if ($initialized) {
132 2
                return;
133
            }
134
135 2
            $initialized = true;
136
137 2
            if (!isset($container['orm.ems.options'])) {
138 2
                $container['orm.ems.options'] = [
139 2
                    'default' => isset($container['orm.em.options']) ? $container['orm.em.options'] : [],
140
                ];
141
            }
142
143 2
            $tmp = $container['orm.ems.options'];
144 2
            foreach ($tmp as $name => &$options) {
145 2
                $options = array_replace($container['orm.em.default_options'], $options);
146
147 2
                if (!isset($container['orm.ems.default'])) {
148 2
                    $container['orm.ems.default'] = $name;
149
                }
150
            }
151
152 2
            $container['orm.ems.options'] = $tmp;
153 2
        });
154
    }
155
156
    /**
157
     * @param Container $container
158
     *
159
     * @return \Closure
160
     */
161
    private function getOrmEmsDefinition(Container $container): \Closure
162
    {
163 2
        return function () use ($container) {
164 2
            $container['orm.ems.options.initializer']();
165
166 2
            $ems = new Container();
167 2
            foreach ($container['orm.ems.options'] as $name => $options) {
168 2
                if ($container['orm.ems.default'] === $name) {
169
                    // we use shortcuts here in case the default has been overridden
170 2
                    $config = $container['orm.em.config'];
171
                } else {
172
                    $config = $container['orm.ems.config'][$name];
173
                }
174
175 2
                $ems[$name] = function () use ($container, $options, $config) {
176 2
                    return EntityManager::create(
177 2
                        $container['dbs'][$options['connection']],
178 2
                        $config,
179 2
                        $container['dbs.event_manager'][$options['connection']]
180
                    );
181 2
                };
182
            }
183
184 2
            return $ems;
185 2
        };
186
    }
187
188
    /**
189
     * @param Container $container
190
     *
191
     * @return \Closure
192
     */
193
    private function getOrmEmsConfigServiceProvider(Container $container): \Closure
194
    {
195 2
        return function () use ($container) {
196 2
            $container['orm.ems.options.initializer']();
197
198 2
            $configs = new Container();
199 2
            foreach ($container['orm.ems.options'] as $name => $options) {
200 2
                $configs[$name] = $this->getOrmEmConfigByNameAndOptionsDefinition($container, $name, $options);
201
            }
202
203 2
            return $configs;
204 2
        };
205
    }
206
207
    /**
208
     * @param Container $container
209
     * @param string    $name
210
     * @param array     $options
211
     *
212
     * @return \Closure
213
     */
214
    private function getOrmEmConfigByNameAndOptionsDefinition(
215
        Container $container,
216
        string $name,
217
        array $options
218
    ): \Closure {
219 2
        return function () use ($container, $name, $options) {
220 2
            $config = new Configuration();
221
222 2
            $container['orm.cache.configurer']($name, $config, $options);
223
224 2
            $config->setProxyDir($container['orm.proxies_dir']);
225 2
            $config->setProxyNamespace($container['orm.proxies_namespace']);
226 2
            $config->setAutoGenerateProxyClasses($container['orm.auto_generate_proxies']);
227
228 2
            $config->setCustomStringFunctions($container['orm.custom.functions.string']);
229 2
            $config->setCustomNumericFunctions($container['orm.custom.functions.numeric']);
230 2
            $config->setCustomDatetimeFunctions($container['orm.custom.functions.datetime']);
231 2
            $config->setCustomHydrationModes($container['orm.custom.hydration_modes']);
232
233 2
            $config->setClassMetadataFactoryName($container['orm.class_metadata_factory_name']);
234 2
            $config->setDefaultRepositoryClassName($container['orm.default_repository_class']);
235
236 2
            $config->setEntityListenerResolver($container['orm.entity_listener_resolver']);
237 2
            $config->setRepositoryFactory($container['orm.repository_factory']);
238
239 2
            $config->setNamingStrategy($container['orm.strategy.naming']);
240 2
            $config->setQuoteStrategy($container['orm.strategy.quote']);
241
242
            /** @var MappingDriverChain $chain */
243 2
            $chain = $container['orm.mapping_driver_chain.locator']($name);
244
245 2
            foreach ((array) $options['mappings'] as $entity) {
246 1
                if (!is_array($entity)) {
247
                    throw new \InvalidArgumentException(
248
                        "The 'orm.em.options' option 'mappings' should be an array of arrays."
249
                    );
250
                }
251
252 1
                if (isset($entity['alias'])) {
253
                    $config->addEntityNamespace($entity['alias'], $entity['namespace']);
254
                }
255
256 1
                $factoryKey = sprintf('orm.mapping_driver.factory.%s', $entity['type']);
257 1
                if (!isset($container[$factoryKey])) {
258
                    throw new \InvalidArgumentException(
259
                        sprintf('There is no driver factory for type "%s"', $entity['type'])
260
                    );
261
                }
262
263 1
                $chain->addDriver($container[$factoryKey]($entity, $config), $entity['namespace']);
264
            }
265
266 2
            $config->setMetadataDriverImpl($chain);
267
268 2
            foreach ((array) $options['types'] as $typeName => $typeClass) {
269
                if (Type::hasType($typeName)) {
270
                    Type::overrideType($typeName, $typeClass);
271
                } else {
272
                    Type::addType($typeName, $typeClass);
273
                }
274
            }
275
276 2
            return $config;
277 2
        };
278
    }
279
280
    /**
281
     * @param Container $container
282
     *
283
     * @return \Closure
284
     */
285
    private function getOrmCacheConfigurerDefinition(Container $container): \Closure
286
    {
287 2
        return $container->protect(function ($name, Configuration $config, $options) use ($container) {
288 2
            $config->setMetadataCacheImpl($container['orm.cache.locator']($name, 'metadata', $options));
289 2
            $config->setQueryCacheImpl($container['orm.cache.locator']($name, 'query', $options));
290 2
            $config->setResultCacheImpl($container['orm.cache.locator']($name, 'result', $options));
291 2
            $config->setHydrationCacheImpl($container['orm.cache.locator']($name, 'hydration', $options));
292 2
        });
293
    }
294
295
    /**
296
     * @param Container $container
297
     *
298
     * @return \Closure
299
     */
300
    private function getOrmCacheLocatorDefinition(Container $container): \Closure
301
    {
302 2
        return $container->protect(function ($name, $cacheName, $options) use ($container) {
303 2
            $cacheNameKey = $cacheName.'_cache';
304
305 2
            if (!isset($options[$cacheNameKey])) {
306 2
                $options[$cacheNameKey] = $container['orm.default_cache'];
307
            }
308
309 2
            if (isset($options[$cacheNameKey]) && !is_array($options[$cacheNameKey])) {
310
                $options[$cacheNameKey] = [
311
                    'driver' => $options[$cacheNameKey],
312
                ];
313
            }
314
315 2
            if (!isset($options[$cacheNameKey]['driver'])) {
316
                throw new \RuntimeException("No driver specified for '$cacheName'");
317
            }
318
319 2
            $driver = $options[$cacheNameKey]['driver'];
320
321 2
            $cacheInstanceKey = 'orm.cache.instances.'.$name.'.'.$cacheName;
322 2
            if (isset($container[$cacheInstanceKey])) {
323
                return $container[$cacheInstanceKey];
324
            }
325
326 2
            $cache = $container['orm.cache.factory']($driver, $options[$cacheNameKey]);
327
328 2
            if (isset($options['cache_namespace']) && $cache instanceof CacheProvider) {
329
                $cache->setNamespace($options['cache_namespace']);
330
            }
331
332 2
            return $container[$cacheInstanceKey] = $cache;
333 2
        });
334
    }
335
336
    /**
337
     * @param Container $container
338
     *
339
     * @return \Closure
340
     */
341
    private function getOrmCacheFactoryApcuDefinition(Container $container): \Closure
342
    {
343 2
        return $container->protect(function () use ($container) {
344
            return new ApcuCache();
345 2
        });
346
    }
347
348
    /**
349
     * @param Container $container
350
     *
351
     * @return \Closure
352
     */
353
    private function getOrmCacheFactoryArrayDefinition(Container $container): \Closure
354
    {
355 2
        return $container->protect(function () use ($container) {
356 2
            return new ArrayCache();
357 2
        });
358
    }
359
360
    /**
361
     * @param Container $container
362
     *
363
     * @return \Closure
364
     */
365
    private function getOrmCacheFactoryFilesystemDefinition(Container $container): \Closure
366
    {
367 2
        return $container->protect(function ($cacheOptions) {
368
            if (empty($cacheOptions['path'])) {
369
                throw new \RuntimeException('FilesystemCache path not defined');
370
            }
371
372
            $cacheOptions += [
373
                'extension' => FilesystemCache::EXTENSION,
374
                'umask' => 0002,
375
            ];
376
377
            return new FilesystemCache($cacheOptions['path'], $cacheOptions['extension'], $cacheOptions['umask']);
378 2
        });
379
    }
380
381
    /**
382
     * @param Container $container
383
     *
384
     * @return \Closure
385
     */
386
    private function getOrmCacheFactoryMemcacheDefinition(Container $container): \Closure
387
    {
388 2
        return $container->protect(function ($cacheOptions) use ($container) {
389
            if (empty($cacheOptions['host']) || empty($cacheOptions['port'])) {
390
                throw new \RuntimeException('Host and port options need to be specified for memcache cache');
391
            }
392
393
            $memcache = new \Memcache();
394
            $memcache->connect($cacheOptions['host'], $cacheOptions['port']);
395
396
            $cache = new MemcacheCache();
397
            $cache->setMemcache($memcache);
398
399
            return $cache;
400 2
        });
401
    }
402
403
    /**
404
     * @param Container $container
405
     *
406
     * @return \Closure
407
     */
408
    private function getOrmCacheFactoryMemcachedDefinition(Container $container): \Closure
409
    {
410 2
        return $container->protect(function ($cacheOptions) use ($container) {
411
            if (empty($cacheOptions['host']) || empty($cacheOptions['port'])) {
412
                throw new \RuntimeException('Host and port options need to be specified for memcached cache');
413
            }
414
415
            $memcached = new \Memcached();
416
            $memcached->addServer($cacheOptions['host'], $cacheOptions['port']);
417
418
            $cache = new MemcachedCache();
419
            $cache->setMemcached($memcached);
420
421
            return $cache;
422 2
        });
423
    }
424
425
    /**
426
     * @param Container $container
427
     *
428
     * @return \Closure
429
     */
430
    private function getOrmCacheFactoryRedisDefinition(Container $container): \Closure
431
    {
432 2
        return $container->protect(function ($cacheOptions) use ($container) {
433
            if (empty($cacheOptions['host']) || empty($cacheOptions['port'])) {
434
                throw new \RuntimeException('Host and port options need to be specified for redis cache');
435
            }
436
437
            $redis = new \Redis();
438
            $redis->connect($cacheOptions['host'], $cacheOptions['port']);
439
440
            if (isset($cacheOptions['password'])) {
441
                $redis->auth($cacheOptions['password']);
442
            }
443
444
            $cache = new RedisCache();
445
            $cache->setRedis($redis);
446
447
            return $cache;
448 2
        });
449
    }
450
451
    /**
452
     * @param Container $container
453
     *
454
     * @return \Closure
455
     */
456
    private function getOrmCacheFactoryXCacheDefinition(Container $container): \Closure
457
    {
458 2
        return $container->protect(function () use ($container) {
459
            return new XcacheCache();
460 2
        });
461
    }
462
463
    /**
464
     * @param Container $container
465
     *
466
     * @return \Closure
467
     */
468
    private function getOrmCacheFactoryDefinition(Container $container): \Closure
469
    {
470 2
        return $container->protect(function ($driver, $cacheOptions) use ($container) {
471 2
            $cacheFactoryKey = 'orm.cache.factory.'.$driver;
472 2
            if (!isset($container[$cacheFactoryKey])) {
473
                throw new \RuntimeException(
474
                    sprintf('Factory "%s" for cache type "%s" not defined', $cacheFactoryKey, $driver)
475
                );
476
            }
477
478 2
            return $container[$cacheFactoryKey]($cacheOptions);
479 2
        });
480
    }
481
482
    /**
483
     * @param Container $container
484
     *
485
     * @return \Closure
486
     */
487
    private function getOrmMappingDriverChainLocatorDefinition(Container $container): \Closure
488
    {
489 2
        return $container->protect(function ($name = null) use ($container) {
490 2
            $container['orm.ems.options.initializer']();
491
492 2
            if (null === $name) {
493
                $name = $container['orm.ems.default'];
494
            }
495
496 2
            $cacheInstanceKey = 'orm.mapping_driver_chain.instances.'.$name;
497 2
            if (isset($container[$cacheInstanceKey])) {
498
                return $container[$cacheInstanceKey];
499
            }
500
501 2
            return $container[$cacheInstanceKey] = $container['orm.mapping_driver_chain.factory']($name);
502 2
        });
503
    }
504
505
    /**
506
     * @param Container $container
507
     *
508
     * @return \Closure
509
     */
510
    private function getOrmMappingDriverChainFactoryDefinition(Container $container): \Closure
511
    {
512 2
        return $container->protect(function () use ($container) {
513 2
            return new MappingDriverChain();
514 2
        });
515
    }
516
517
    /**
518
     * @param Container $container
519
     *
520
     * @return \Closure
521
     */
522
    private function getOrmNamingStrategyDefinition(Container $container): \Closure
523
    {
524 2
        return function () use ($container) {
525 2
            return new DefaultNamingStrategy();
526 2
        };
527
    }
528
529
    /**
530
     * @param Container $container
531
     *
532
     * @return \Closure
533
     */
534
    private function getOrmQuoteStrategyDefinition(Container $container): \Closure
535
    {
536 2
        return function () use ($container) {
537 2
            return new DefaultQuoteStrategy();
538 2
        };
539
    }
540
541
    /**
542
     * @param Container $container
543
     *
544
     * @return \Closure
545
     */
546
    private function getOrmEntityListenerResolverDefinition(Container $container): \Closure
547
    {
548 2
        return function () use ($container) {
549 2
            return new DefaultEntityListenerResolver();
550 2
        };
551
    }
552
553
    /**
554
     * @param Container $container
555
     *
556
     * @return \Closure
557
     */
558
    private function getOrmRepositoryFactoryDefinition(Container $container): \Closure
559
    {
560 2
        return function () use ($container) {
561 2
            return new DefaultRepositoryFactory();
562 2
        };
563
    }
564
565
    /**
566
     * @param Container $container
567
     *
568
     * @return \Closure
569
     */
570
    private function getOrmEmDefinition(Container $container): \Closure
571
    {
572 2
        return function () use ($container) {
573 2
            $ems = $container['orm.ems'];
574
575 2
            return $ems[$container['orm.ems.default']];
576 2
        };
577
    }
578
579
    /**
580
     * @param Container $container
581
     *
582
     * @return \Closure
583
     */
584
    private function getOrmEmConfigDefinition(Container $container): \Closure
585
    {
586 2
        return function () use ($container) {
587 2
            $configs = $container['orm.ems.config'];
588
589 2
            return $configs[$container['orm.ems.default']];
590 2
        };
591
    }
592
}
593