ReleaseRecordedEventsMiddleware   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 51
c 0
b 0
f 0
wmc 4
lcom 1
cbo 2
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A execute() 0 16 3
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
}