DatabaseManager::getEntityManager()   B
last analyzed

Complexity

Conditions 5
Paths 12

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
cc 5
eloc 16
nc 12
nop 1
1
<?php
2
3
namespace Core;
4
5
use Doctrine\ORM\Tools\Setup;
6
use Doctrine\ORM\EntityManager;
7
8
use \Exception;
9
use \RuntimeException;
10
11
class DatabaseManager
12
{
13
    protected static $config = [];
14
    private static $entityManagers = [];
15
16
    public static function setConfig(array $config)
17
    {
18
        self::$config = $config;
19
    }
20
21
    /**
22
     * @return EntityManager
23
     */
24
    public static function getEntityManager($connectionName = null)
25
    {
26
        $connectionName = $connectionName ?: self::$config['defaultConnection'];
27
28
        if (isset(self::$entityManagers[$connectionName])) {
29
            return self::$entityManagers[$connectionName];
30
        }
31
32
        try {
33
            $config = Setup::createAnnotationMetadataConfiguration(
34
                self::$config['entityPath'],
35
                self::$config['devMode']
36
            );
37
            $entityManager = EntityManager::create(self::$config['connections'][$connectionName], $config);
38
            $entityManager->getConnection()->connect();
39
40
            self::$entityManagers[$connectionName] = $entityManager;
41
42
            return $entityManager;
43
        } catch (Exception $e) {
44
            throw self::$config['devMode']
45
                ? $e
46
                : new RuntimeException('Error raised when trying to connect database');
47
        }
48
    }
49
}
50