EventEmitterMiddleware::execute()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
c 0
b 0
f 0
rs 9.9666
cc 1
nc 1
nop 2
1
<?php
2
3
namespace hiapi\middlewares;
4
5
use hiapi\event\EventStorageInterface;
6
use League\Event\EmitterInterface;
7
use League\Event\EventInterface;
8
use League\Tactician\Middleware;
9
use Psr\Log\LoggerInterface;
10
11
/**
12
 * Class EventEmitterMiddleware
13
 *
14
 * @author Dmytro Naumenko <[email protected]>
15
 */
16
class EventEmitterMiddleware implements Middleware
17
{
18
    /**
19
     * @var \hiapi\event\EventStorageInterface
20
     */
21
    private $eventStorage;
22
    /**
23
     * @var EmitterInterface
24
     */
25
    private $emitter;
26
    /**
27
     * @var LoggerInterface
28
     */
29
    private $logger;
30
31
    public function __construct(EventStorageInterface $eventStorage, EmitterInterface $emitter, LoggerInterface $logger)
32
    {
33
        $this->eventStorage = $eventStorage;
34
        $this->emitter = $emitter;
35
        $this->logger = $logger;
36
    }
37
38
    /**
39
     * @param object $command
40
     * @param callable $next
41
     *
42
     * @return mixed
43
     */
44
    public function execute($command, callable $next)
45
    {
46
        $result = $next($command);
47
48
        $events = $this->eventStorage->release();
49
        $this->emitEvents($events);
50
51
        return $result;
52
    }
53
54
    /**
55
     * @param EventInterface[] $events
56
     */
57
    private function emitEvents(array $events = []): void
58
    {
59
        foreach ($events as $event) {
60
            try {
61
                $this->emitter->emit($event);
62
            } catch (\Exception $exception) {
63
                $this->logger->error("Failed to handle event {$event->getName()}: {$exception->getMessage()}", [
64
                    'exception' => $exception,
65
                ]);
66
            }
67
        }
68
    }
69
}
70