|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Copyright (c) 2017 Constantin Galbenu <[email protected]> |
|
4
|
|
|
*/ |
|
5
|
|
|
|
|
6
|
|
|
namespace Gica\Cqrs\Saga; |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
|
|
use Gica\Cqrs\Event\EventSubscriber; |
|
10
|
|
|
use Gica\Cqrs\Event\EventWithMetaData; |
|
11
|
|
|
use Gica\Cqrs\Saga\SagaEventTrackerRepository\ConcurentModificationException; |
|
12
|
|
|
|
|
13
|
|
|
class SagasOnlyOnceEventDispatcher implements \Gica\Cqrs\Event\EventDispatcher |
|
14
|
|
|
{ |
|
15
|
|
|
|
|
16
|
|
|
/** @var EventSubscriber */ |
|
17
|
|
|
private $eventSubscriber; |
|
18
|
|
|
/** |
|
19
|
|
|
* @var SagaEventTrackerRepository |
|
20
|
|
|
*/ |
|
21
|
|
|
private $trackerRepository; |
|
22
|
|
|
|
|
23
|
3 |
|
public function __construct( |
|
24
|
|
|
SagaEventTrackerRepository $trackerRepository, |
|
25
|
|
|
EventSubscriber $eventSubscriber |
|
26
|
|
|
) |
|
27
|
|
|
{ |
|
28
|
3 |
|
$this->eventSubscriber = $eventSubscriber; |
|
29
|
3 |
|
$this->trackerRepository = $trackerRepository; |
|
30
|
3 |
|
} |
|
31
|
|
|
|
|
32
|
3 |
|
public function dispatchEvent(EventWithMetaData $eventWithMetaData) |
|
33
|
|
|
{ |
|
34
|
3 |
|
$listeners = $this->eventSubscriber->getListenersForEvent($eventWithMetaData->getEvent()); |
|
35
|
|
|
|
|
36
|
3 |
|
foreach ($listeners as $listener) { |
|
37
|
3 |
|
$metaData = $eventWithMetaData->getMetaData(); |
|
38
|
|
|
|
|
39
|
3 |
|
if (is_array($listener)) { |
|
40
|
3 |
|
$saga = $listener[0]; |
|
41
|
|
|
|
|
42
|
3 |
|
if (!$this->trackerRepository->isEventAlreadyDispatched(get_class($saga), $metaData->getSequence(), $metaData->getIndex())) { |
|
43
|
|
|
try { |
|
44
|
2 |
|
$this->trackerRepository->beginProcessingEventBySaga(get_class($saga), $metaData->getSequence(), $metaData->getIndex()); |
|
45
|
1 |
|
call_user_func($listener, $eventWithMetaData->getEvent(), $metaData); |
|
46
|
1 |
|
$this->trackerRepository->endProcessingEventBySaga(get_class($saga), $metaData->getSequence(), $metaData->getIndex()); |
|
47
|
1 |
|
} catch (ConcurentModificationException $exception) { |
|
48
|
3 |
|
continue; |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
} |