|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Shared Kernel library. |
|
5
|
|
|
* |
|
6
|
|
|
* Copyright (c) 2016-present LIN3S <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
declare(strict_types=1); |
|
13
|
|
|
|
|
14
|
|
|
namespace LIN3S\SharedKernel\Infrastructure\Application\Tactician\Middlewares; |
|
15
|
|
|
|
|
16
|
|
|
use League\Tactician\Middleware; |
|
17
|
|
|
use LIN3S\SharedKernel\Domain\Event\CollectInMemoryDomainEventsSubscriber; |
|
18
|
|
|
use LIN3S\SharedKernel\Domain\Event\DomainEventPublisher; |
|
19
|
|
|
use LIN3S\SharedKernel\Event\EventStore; |
|
20
|
|
|
use LIN3S\SharedKernel\Event\StoredEvent; |
|
21
|
|
|
use LIN3S\SharedKernel\Event\StreamName; |
|
22
|
|
|
use LIN3S\SharedKernel\Event\StreamVersion; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @author Beñat Espiña <[email protected]> |
|
26
|
|
|
*/ |
|
27
|
|
|
class AppendDomainEventsToStoreMiddleware implements Middleware |
|
28
|
|
|
{ |
|
29
|
|
|
private $eventStore; |
|
30
|
|
|
|
|
31
|
|
|
public function __construct(EventStore $eventStore) |
|
32
|
|
|
{ |
|
33
|
|
|
$this->eventStore = $eventStore; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public function execute($command, callable $next) |
|
37
|
|
|
{ |
|
38
|
|
|
$collectDomainEventsSubscriber = new CollectInMemoryDomainEventsSubscriber(); |
|
39
|
|
|
DomainEventPublisher::instance()->subscribe($collectDomainEventsSubscriber); |
|
40
|
|
|
|
|
41
|
|
|
$returnValue = $next($command); |
|
42
|
|
|
|
|
43
|
|
|
$publishableEvents = $collectDomainEventsSubscriber->events(); |
|
44
|
|
|
$storedEvents = []; |
|
45
|
|
|
foreach ($publishableEvents as $publishableEvent) { |
|
46
|
|
|
$storedEvents[] = new StoredEvent( |
|
47
|
|
|
$publishableEvent->event(), |
|
48
|
|
|
StreamName::from($publishableEvent->aggregateId(), $publishableEvent->name()), |
|
49
|
|
|
$this->streamVersion() |
|
50
|
|
|
); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
$this->eventStore->append(...$storedEvents); |
|
54
|
|
|
|
|
55
|
|
|
return $returnValue; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
private function streamVersion() : StreamVersion |
|
59
|
|
|
{ |
|
60
|
|
|
return new StreamVersion(1); // TODO: This value is hardcoded for now. |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|