SyncEventDispatcher::flush()   A
last analyzed

Complexity

Conditions 4
Paths 22

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 9.376
c 0
b 0
f 0
cc 4
nc 22
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Explicit Architecture POC,
7
 * which is created on top of the Symfony Demo application.
8
 *
9
 * (c) Herberto Graça <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Acme\App\Infrastructure\EventDispatcher;
16
17
use Acme\App\Core\Port\EventDispatcher\BufferedEventDispatcherInterface;
18
use Acme\App\Core\Port\Lock\LockManagerInterface;
19
use Acme\App\Core\Port\Persistence\TransactionServiceInterface;
20
use Acme\App\Core\SharedKernel\Port\EventDispatcher\EventInterface;
21
use Acme\PhpExtension\Helper\TypeHelper;
22
use Acme\PhpExtension\ObjectDispatcher\AbstractDispatcher;
23
use Psr\Log\LoggerInterface;
24
use Psr\Log\NullLogger;
25
use Throwable;
26
27
/**
28
 * Conceptually, the code triggering an event must not rely on the logic that the event triggers. So that logic doesn't
29
 * need to, and should not, be executed in-line with the code triggering it.
30
 * This means that, technically, all events could be asynchronous, meaning that the logic they trigger could be
31
 * executed after the HTTP request has been handled and the HTTP response was sent back to the client. Ideally in
32
 * another process, started by a message bus/queue.
33
 * However, for UX reasons, sometimes we want to handle an event in the same request where it is triggered, so that we
34
 * make sure the user can see the expected results in the next request he makes.
35
 *
36
 * Thus, we have the need for two types of event dispatchers (which can be behind a proxy dispatcher):
37
 *      - A SyncEventDispatcher which dispatcher the events in the same request
38
 *      - An AsyncEventDispatcher, which sends the events to a message bus so they will be executed later, in parallel
39
 *
40
 * Nevertheless, despite the SyncEventDispatcher running the event listeners in the same HTTP request as the code that
41
 * triggered the events, it does not mean it must run those listeners in-line with the code that triggered the events.
42
 * Thus, this SyncEventDispatcher will put the events in a buffer, and it will flush them all to the listeners after
43
 * the system handles the HTTP request, and just before sending the HTTP response back to the client.
44
 */
45
final class SyncEventDispatcher extends AbstractDispatcher implements BufferedEventDispatcherInterface
46
{
47
    /**
48
     * @var [EventInterface,[]][]
49
     */
50
    private $eventBuffer = [];
51
52
    /**
53
     * @var TransactionServiceInterface
54
     */
55
    private $transactionService;
56
57
    /**
58
     * @var LockManagerInterface
59
     */
60
    private $lockManager;
61
62
    /**
63
     * @var LoggerInterface
64
     */
65
    private $logger;
66
67
    public function __construct(
68
        TransactionServiceInterface $transactionService,
69
        LockManagerInterface $lockManager,
70
        LoggerInterface $logger = null
71
    ) {
72
        $this->transactionService = $transactionService;
73
        $this->lockManager = $lockManager;
74
        $this->logger = $logger ?? new NullLogger();
75
    }
76
77
    public function dispatch(EventInterface $event, array $metadata = []): void
78
    {
79
        $this->eventBuffer[] = [$event, $metadata];
80
    }
81
82
    public function flush(): void
83
    {
84
        foreach ($this->eventBuffer as [$event, $metadata]) {
85
            foreach ($this->getDestinationListForObject(\get_class($event)) as $listener) {
86
                /*
87
                 * Since these events are going to be handled outside of the main use case transaction,
88
                 * they will also be executed outside of the request transaction (after it is closed) so we will need
89
                 * to open a new transaction for the event listeners.
90
                 * Furthermore, since each event is independent from each other, we need to open a new transaction
91
                 * for each individual event listener.
92
                 */
93
                try {
94
                    $this->transactionService->startTransaction();
95
                    $listener($event, $metadata);
0 ignored issues
show
Bug introduced by
The variable $event does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $metadata does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
96
                    $this->transactionService->finishTransaction();
97
                } catch (Throwable $e) {
98
                    /*
99
                     * We simply log the exception and continue because if we rethrow the exception, the remaining
100
                     * event listeners will not be triggered.
101
                     */
102
                    $this->logger->error(
103
                        'Error occurred while handling event \'' . TypeHelper::getType($event)
104
                        . "' with listener '" . TypeHelper::getType($listener) . "'.\n"
105
                        . 'Exception message: ' . $e->getMessage() . "\n"
106
                        . 'Exception trace: ' . $e->getTraceAsString() . "\n"
107
                    );
108
                    $this->transactionService->rollbackTransaction();
109
                } finally {
110
                    // We release all locks here, so that they can be reacquired when processing the next event
111
                    $this->lockManager->releaseAll();
112
                }
113
            }
114
        }
115
    }
116
117
    public function reset(): void
118
    {
119
        $this->eventBuffer = [];
120
    }
121
}
122