streamVersion()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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