|
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
|
1 |
|
public function __invoke(ContainerInterface $container): EntityManager |
|
23
|
|
|
{ |
|
24
|
1 |
|
$globalConfig = $container->get('config'); |
|
25
|
1 |
|
$isDevMode = (bool) ($globalConfig['debug'] ?? false); |
|
26
|
1 |
|
$cache = $container->has(Cache::class) ? $container->get(Cache::class) : new ArrayCache(); |
|
27
|
1 |
|
$emConfig = $globalConfig['entity_manager'] ?? []; |
|
28
|
1 |
|
$connectionConfig = $emConfig['connection'] ?? []; |
|
29
|
1 |
|
$ormConfig = $emConfig['orm'] ?? []; |
|
30
|
|
|
|
|
31
|
1 |
|
$this->registerTypes($ormConfig); |
|
32
|
|
|
|
|
33
|
1 |
|
$config = Setup::createConfiguration($isDevMode, $ormConfig['proxies_dir'] ?? null, $cache); |
|
34
|
1 |
|
$config->setMetadataDriverImpl(new PHPDriver($ormConfig['entities_mappings'] ?? [])); |
|
35
|
|
|
|
|
36
|
1 |
|
return EntityManager::create($connectionConfig, $config); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @throws DBALException |
|
41
|
|
|
*/ |
|
42
|
1 |
|
private function registerTypes(array $ormConfig): void |
|
43
|
|
|
{ |
|
44
|
1 |
|
$types = $ormConfig['types'] ?? []; |
|
45
|
|
|
|
|
46
|
1 |
|
foreach ($types as $name => $className) { |
|
47
|
1 |
|
if (! Type::hasType($name)) { |
|
48
|
|
|
Type::addType($name, $className); |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|