|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Dsantang\DomainEventsDoctrine\OutboxEvents; |
|
6
|
|
|
|
|
7
|
|
|
use Doctrine\ORM\Event\OnFlushEventArgs; |
|
8
|
|
|
use Doctrine\ORM\UnitOfWork; |
|
9
|
|
|
use Dsantang\DomainEvents\Counter; |
|
10
|
|
|
use Dsantang\DomainEvents\EventAware; |
|
11
|
|
|
use function array_filter; |
|
12
|
|
|
use function array_merge; |
|
13
|
|
|
use function ksort; |
|
14
|
|
|
|
|
15
|
|
|
final class OutboxOrderedDoctrineEvents |
|
16
|
|
|
{ |
|
17
|
|
|
/** @var OutboxTransformer */ |
|
18
|
|
|
private $transformer; |
|
19
|
|
|
|
|
20
|
|
|
/** @var OutboxEntityPersistence */ |
|
21
|
|
|
private $entityPersistence; |
|
22
|
|
|
|
|
23
|
1 |
|
public function __construct( |
|
24
|
|
|
OutboxTransformer $transformer, |
|
25
|
|
|
OutboxEntityPersistence $entityPersistence |
|
26
|
|
|
) { |
|
27
|
1 |
|
$this->transformer = $transformer; |
|
28
|
1 |
|
$this->entityPersistence = $entityPersistence; |
|
29
|
1 |
|
} |
|
30
|
|
|
|
|
31
|
1 |
|
public function onFlush(OnFlushEventArgs $eventArgs) : void |
|
32
|
|
|
{ |
|
33
|
1 |
|
$entityManager = $eventArgs->getEntityManager(); |
|
34
|
|
|
|
|
35
|
1 |
|
$events = []; |
|
36
|
|
|
|
|
37
|
1 |
|
foreach (self::getEventAwareEntities($entityManager->getUnitOfWork()) as $entity) { |
|
38
|
|
|
$events += array_filter($entity->expelRecordedEvents(), static function ($event) { |
|
39
|
1 |
|
return $event instanceof OutboxEvent; |
|
40
|
1 |
|
}); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
1 |
|
ksort($events); |
|
44
|
|
|
|
|
45
|
1 |
|
Counter::reset(); |
|
46
|
|
|
|
|
47
|
1 |
|
foreach ($events as $event) { |
|
48
|
1 |
|
$this->entityPersistence->persist($this->transformer->transform($event)); |
|
49
|
|
|
} |
|
50
|
1 |
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @return EventAware[] |
|
54
|
|
|
*/ |
|
55
|
1 |
|
private static function getEventAwareEntities(UnitOfWork $unitOfWork) : array |
|
56
|
|
|
{ |
|
57
|
1 |
|
$entities = array_merge( |
|
58
|
1 |
|
$unitOfWork->getScheduledEntityInsertions(), |
|
59
|
1 |
|
$unitOfWork->getScheduledEntityUpdates(), |
|
60
|
1 |
|
$unitOfWork->getScheduledEntityDeletions() |
|
61
|
|
|
); |
|
62
|
|
|
|
|
63
|
|
|
return array_filter($entities, static function ($entity) { |
|
64
|
1 |
|
return $entity instanceof EventAware; |
|
65
|
1 |
|
}); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|