Completed
Push — master ( ea11b7...4be545 )
by Beñat
01:45
created

DomainEventsPublicationMiddleware::streamVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
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\Domain\Model\DomainEventCollection;
20
use LIN3S\SharedKernel\Event\AggregateId;
21
use LIN3S\SharedKernel\Event\EventStore;
22
use LIN3S\SharedKernel\Event\Stream;
23
use LIN3S\SharedKernel\Event\StreamName;
24
use LIN3S\SharedKernel\Event\StreamVersion;
25
26
/**
27
 * @author Beñat Espiña <[email protected]>
28
 */
29
class DomainEventsPublicationMiddleware implements Middleware
30
{
31
    private $eventStore;
32
33
    public function __construct(EventStore $eventStore)
34
    {
35
        $this->eventStore = $eventStore;
36
    }
37
38
    public function execute($command, callable $next)
39
    {
40
        $domainEventPublisher = DomainEventPublisher::instance();
41
        $collectDomainEventsSubscriber = new CollectInMemoryDomainEventsSubscriber();
42
        $domainEventPublisher->subscribe($collectDomainEventsSubscriber);
43
44
        $returnValue = $next($command);
45
46
        $eventsPerAggregate = $collectDomainEventsSubscriber->events();
47
        foreach ($eventsPerAggregate as $name => $aggregate) {
48
            foreach ($aggregate as $aggregateId => $domainEvents) {
49
                $this->eventStore->append(
50
                    new Stream(
51
                        new StreamName(AggregateId::generate($aggregateId), $name),
52
                        $this->streamVersion(),
53
                        new DomainEventCollection($domainEvents)
54
                    )
55
                );
56
            }
57
        }
58
59
        return $returnValue;
60
    }
61
62
    private function streamVersion() : StreamVersion
63
    {
64
        return new StreamVersion(1);    // TODO: This value is hardcoded for now.
65
    }
66
}
67