1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Savers; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
6
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Entity\Interfaces\EntityInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class EntitySaver |
10
|
|
|
* |
11
|
|
|
* Generic Entity Saver |
12
|
|
|
* |
13
|
|
|
* Can be used to save any entities as required |
14
|
|
|
* |
15
|
|
|
* For Entity specific saving logic, you should create an Entity Specific Saver |
16
|
|
|
* that subclasses: |
17
|
|
|
* \EdmondsCommerce\DoctrineStaticMeta\Entity\Savers\AbstractEntitySpecificSaver |
18
|
|
|
* |
19
|
|
|
* @package EdmondsCommerce\DoctrineStaticMeta\Entity\Savers |
20
|
|
|
*/ |
21
|
|
|
class EntitySaver implements EntitySaverInterface |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var EntityManagerInterface |
25
|
|
|
*/ |
26
|
|
|
protected $entityManager; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var string |
30
|
|
|
*/ |
31
|
|
|
protected $entityFqn; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* AbstractSaver constructor. |
35
|
|
|
* |
36
|
|
|
* @param EntityManagerInterface $entityManager |
37
|
|
|
*/ |
38
|
|
|
public function __construct( |
39
|
|
|
EntityManagerInterface $entityManager |
40
|
|
|
) { |
41
|
|
|
$this->entityManager = $entityManager; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param EntityInterface $entity |
46
|
|
|
* |
47
|
|
|
* @throws \Doctrine\DBAL\DBALException |
48
|
|
|
*/ |
49
|
|
|
public function save(EntityInterface $entity): void |
50
|
|
|
{ |
51
|
|
|
$this->saveAll([$entity]); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param array|EntityInterface[] $entities |
56
|
|
|
* |
57
|
|
|
* @throws \Doctrine\DBAL\DBALException |
58
|
|
|
*/ |
59
|
|
|
public function saveAll(array $entities): void |
60
|
|
|
{ |
61
|
|
|
if ([] === $entities) { |
62
|
|
|
return; |
63
|
|
|
} |
64
|
|
|
foreach ($entities as $entity) { |
65
|
|
|
if (false === $entity instanceof EntityInterface) { |
66
|
|
|
throw new \InvalidArgumentException( |
67
|
|
|
'Found invalid $entity was not an EntityInterface, was ' . \get_class($entity) |
68
|
|
|
); |
69
|
|
|
} |
70
|
|
|
$this->entityManager->persist($entity); |
71
|
|
|
} |
72
|
|
|
$this->entityManager->flush(); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @param EntityInterface $entity |
77
|
|
|
*/ |
78
|
|
|
public function remove(EntityInterface $entity): void |
79
|
|
|
{ |
80
|
|
|
$this->removeAll([$entity]); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @param array|EntityInterface[] $entities |
85
|
|
|
*/ |
86
|
|
|
public function removeAll(array $entities): void |
87
|
|
|
{ |
88
|
|
|
if ([] === $entities) { |
89
|
|
|
return; |
90
|
|
|
} |
91
|
|
|
foreach ($entities as $entity) { |
92
|
|
|
$this->entityManager->remove($entity); |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
$this->entityManager->flush(); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|