1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Created by PhpStorm. |
4
|
|
|
* User: siim |
5
|
|
|
* Date: 16.02.19 |
6
|
|
|
* Time: 19:28 |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Sf4\Api\Repository; |
10
|
|
|
|
11
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
12
|
|
|
use Sf4\Api\Utils\Traits\EntityManagerTrait; |
13
|
|
|
|
14
|
|
|
class RepositoryFactory |
15
|
|
|
{ |
16
|
|
|
|
17
|
|
|
use EntityManagerTrait; |
18
|
|
|
|
19
|
|
|
/** @var array $entities */ |
20
|
|
|
protected $entities; |
21
|
|
|
|
22
|
|
|
/** @var array $repositories */ |
23
|
|
|
protected $repositories = []; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* RepositoryFactory constructor. |
27
|
|
|
* @param EntityManagerInterface $entityManager |
28
|
|
|
* @param array $entities |
29
|
|
|
*/ |
30
|
|
|
public function __construct(EntityManagerInterface $entityManager, array $entities = []) |
31
|
|
|
{ |
32
|
|
|
$this->setEntityManager($entityManager); |
33
|
|
|
$this->entities = $entities; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @param array $entities |
38
|
|
|
*/ |
39
|
|
|
public function addEntities(array $entities): void |
40
|
|
|
{ |
41
|
|
|
foreach ($entities as $tableName => $entityClass) { |
42
|
|
|
$this->addEntity($tableName, $entityClass); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param string $tableName |
48
|
|
|
* @param string $entityClass |
49
|
|
|
*/ |
50
|
|
|
public function addEntity(string $tableName, string $entityClass): void |
51
|
|
|
{ |
52
|
|
|
$this->entities[$tableName] = $entityClass; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param string $tableName |
57
|
|
|
* @return RepositoryInterface|null |
58
|
|
|
*/ |
59
|
|
|
public function create(string $tableName): ?RepositoryInterface |
60
|
|
|
{ |
61
|
|
|
if (array_key_exists($tableName, $this->repositories)) { |
62
|
|
|
return $this->repositories[$tableName]; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$entityClass = $this->getEntityClass($tableName); |
66
|
|
|
if ($entityClass) { |
67
|
|
|
$repository = $this->getEntityManager()->getRepository($entityClass); |
68
|
|
|
if ($repository instanceof RepositoryInterface) { |
69
|
|
|
$this->repositories[$tableName] = $repository; |
70
|
|
|
return $repository; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return null; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param string $tableName |
79
|
|
|
* @return string|null |
80
|
|
|
*/ |
81
|
|
|
public function getEntityClass(string $tableName): ?string |
82
|
|
|
{ |
83
|
|
|
return $this->entities[$tableName] ?? null; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|