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 EntityManagerInterface $entityManager */ |
20
|
|
|
protected $entityManager; |
21
|
|
|
|
22
|
|
|
/** @var array $entities */ |
23
|
|
|
protected $entities; |
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) |
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) |
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
|
|
|
$entityClass = $this->getEntityClass($tableName); |
62
|
|
|
if ($entityClass) { |
63
|
|
|
$repository = $this->getEntityManager()->getRepository($entityClass); |
64
|
|
|
if ($repository instanceof RepositoryInterface) { |
65
|
|
|
return $repository; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return null; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param string $tableName |
74
|
|
|
* @return string|null |
75
|
|
|
*/ |
76
|
|
|
public function getEntityClass(string $tableName): ?string |
77
|
|
|
{ |
78
|
|
|
if (isset($this->entities[$tableName])) { |
79
|
|
|
return $this->entities[$tableName]; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return null; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|