Completed
Push — master ( 8fab1b...fcd699 )
by Alejandro
16s queued 11s
created

EntityManagerFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
eloc 15
dl 0
loc 33
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 15 2
A registerTypes() 0 7 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Common\Doctrine;
5
6
use Doctrine\Common\Cache\ArrayCache;
7
use Doctrine\Common\Cache\Cache;
8
use Doctrine\Common\Persistence\Mapping\Driver\PHPDriver;
9
use Doctrine\DBAL\DBALException;
10
use Doctrine\DBAL\Types\Type;
11
use Doctrine\ORM\EntityManager;
12
use Doctrine\ORM\ORMException;
13
use Doctrine\ORM\Tools\Setup;
14
use Psr\Container\ContainerInterface;
15
16
class EntityManagerFactory
17
{
18
    /**
19
     * @throws ORMException
20
     * @throws DBALException
21
     */
22 5
    public function __invoke(ContainerInterface $container): EntityManager
23
    {
24 5
        $globalConfig = $container->get('config');
25 5
        $isDevMode = (bool) ($globalConfig['debug'] ?? false);
26 5
        $cache = $container->has(Cache::class) ? $container->get(Cache::class) : new ArrayCache();
27 5
        $emConfig = $globalConfig['entity_manager'] ?? [];
28 5
        $connectionConfig = $emConfig['connection'] ?? [];
29 5
        $ormConfig = $emConfig['orm'] ?? [];
30
31 5
        $this->registerTypes($ormConfig);
32
33 5
        $config = Setup::createConfiguration($isDevMode, $ormConfig['proxies_dir'] ?? null, $cache);
34 5
        $config->setMetadataDriverImpl(new PHPDriver($ormConfig['entities_mappings'] ?? []));
35
36 5
        return EntityManager::create($connectionConfig, $config);
37
    }
38
39
    /**
40
     * @throws DBALException
41
     */
42 5
    private function registerTypes(array $ormConfig): void
43
    {
44 5
        $types = $ormConfig['types'] ?? [];
45
46 5
        foreach ($types as $name => $className) {
47 5
            if (! Type::hasType($name)) {
48 5
                Type::addType($name, $className);
49
            }
50
        }
51
    }
52
}
53