ReleaseRecordedEventsMiddleware::execute()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 9
nc 3
nop 2
1
<?php
2
3
namespace BornFree\TacticianDomainEvent\Middleware;
4
5
use BornFree\TacticianDomainEvent\EventDispatcher\EventDispatcherInterface;
6
use BornFree\TacticianDomainEvent\Recorder\ContainsRecordedEvents;
7
use League\Tactician\Middleware;
8
9
class ReleaseRecordedEventsMiddleware implements Middleware
10
{
11
    /**
12
     * @var ContainsRecordedEvents
13
     */
14
    private $eventRecorder;
15
16
    /**
17
     * @var EventDispatcherInterface
18
     */
19
    private $eventDispatcher;
20
21
    /**
22
     * ReleaseRecorderEventsMiddleware constructor.
23
     *
24
     * @param ContainsRecordedEvents $eventRecorder
25
     * @param EventDispatcherInterface $eventDispatcher
26
     */
27
    public function __construct(ContainsRecordedEvents $eventRecorder, EventDispatcherInterface $eventDispatcher)
28
    {
29
        $this->eventRecorder = $eventRecorder;
30
        $this->eventDispatcher = $eventDispatcher;
31
    }
32
33
    /**
34
     * Dispatches all the recorded events in the EventBus and erases them
35
     *
36
     * @param object $command
37
     * @param callable $next
38
     *
39
     * @return void
40
     *
41
     * @throws \Exception
42
     */
43
    public function execute($command, callable $next)
44
    {
45
        try {
46
            $next($command);
47
        } catch (\Exception $exception) {
48
            $this->eventRecorder->eraseEvents();
49
50
            throw $exception;
51
        }
52
53
        $recordedEvents = $this->eventRecorder->releaseEvents();
54
55
        foreach ($recordedEvents as $event) {
56
            $this->eventDispatcher->dispatch($event);
57
        }
58
    }
59
}