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