|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Silverback\ApiComponentBundle\DataFixtures; |
|
6
|
|
|
|
|
7
|
|
|
use Doctrine\Common\Collections\ArrayCollection; |
|
8
|
|
|
use Doctrine\Common\DataFixtures\AbstractFixture as BaseAbstractFixture; |
|
9
|
|
|
use Doctrine\Common\Persistence\ObjectManager; |
|
10
|
|
|
use Silverback\ApiComponentBundle\Exception\InvalidEntityException; |
|
11
|
|
|
use Symfony\Component\Validator\Validator\ValidatorInterface; |
|
12
|
|
|
|
|
13
|
|
|
abstract class AbstractFixture extends BaseAbstractFixture |
|
14
|
|
|
{ |
|
15
|
|
|
protected $validator; |
|
16
|
|
|
/** @var ArrayCollection */ |
|
17
|
|
|
private $entities; |
|
18
|
|
|
|
|
19
|
|
|
public function __construct(ValidatorInterface $validator) |
|
20
|
|
|
{ |
|
21
|
|
|
$this->validator = $validator; |
|
22
|
|
|
$this->resetEntities(); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
private function resetEntities(): void |
|
26
|
|
|
{ |
|
27
|
|
|
$this->entities = new ArrayCollection(); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
|
|
31
|
|
|
protected function addEntities(array $entities): void |
|
32
|
|
|
{ |
|
33
|
|
|
foreach ($entities as $entity) { |
|
34
|
|
|
$this->addEntity($entity); |
|
35
|
|
|
} |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
private function validateEntity(object $entity): void |
|
39
|
|
|
{ |
|
40
|
|
|
$errors = $this->validator->validate($entity); |
|
41
|
|
|
if (\count($errors)) { |
|
42
|
|
|
throw new InvalidEntityException($errors); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
protected function addEntity(object $entity, bool $skipValidation = false): void |
|
47
|
|
|
{ |
|
48
|
|
|
if (!$skipValidation) { |
|
49
|
|
|
$this->validateEntity($entity); |
|
50
|
|
|
} |
|
51
|
|
|
$this->entities->add($entity); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
protected function flushEntity(ObjectManager $manager, object $entity, bool $skipValidation = false): void |
|
55
|
|
|
{ |
|
56
|
|
|
if (!$skipValidation) { |
|
57
|
|
|
$this->validateEntity($entity); |
|
58
|
|
|
} |
|
59
|
|
|
$this->flush($manager, new ArrayCollection([ $entity ])); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
protected function flush(ObjectManager $manager, ?ArrayCollection $entities = null): void |
|
63
|
|
|
{ |
|
64
|
|
|
$useEntityArgument = $entities !== null; |
|
65
|
|
|
$flushingEntities = $useEntityArgument ? $entities : $this->entities; |
|
66
|
|
|
foreach ($flushingEntities as $entity) { |
|
67
|
|
|
$manager->persist($entity); |
|
68
|
|
|
} |
|
69
|
|
|
$manager->flush(); |
|
70
|
|
|
if (!$useEntityArgument) { |
|
71
|
|
|
$this->resetEntities(); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|