CouchDbStreamStorage   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 7
Bugs 1 Features 0
Metric Value
eloc 15
c 7
b 1
f 0
dl 0
loc 37
ccs 0
cts 14
cp 0
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 10 1
A append() 0 15 3
A __construct() 0 3 1
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of the daikon-cqrs/couchdb-adapter project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Daikon\CouchDb\Storage;
10
11
use Daikon\Dbal\Exception\DocumentConflict;
12
use Daikon\EventSourcing\Aggregate\AggregateIdInterface;
13
use Daikon\EventSourcing\Aggregate\AggregateRevision;
14
use Daikon\EventSourcing\EventStore\Commit\CommitInterface;
15
use Daikon\EventSourcing\EventStore\Storage\StorageError;
16
use Daikon\EventSourcing\EventStore\Storage\StorageResultInterface;
17
use Daikon\EventSourcing\EventStore\Storage\StorageSuccess;
18
use Daikon\EventSourcing\EventStore\Storage\StreamStorageInterface;
19
use Daikon\EventSourcing\EventStore\Stream\Sequence;
20
use Daikon\EventSourcing\EventStore\Stream\Stream;
21
use Daikon\EventSourcing\EventStore\Stream\StreamInterface;
22
23
final class CouchDbStreamStorage implements StreamStorageInterface
24
{
25
    private CouchDbStorageAdapter $storageAdapter;
26
27
    public function __construct(CouchDbStorageAdapter $storageAdapter)
28
    {
29
        $this->storageAdapter = $storageAdapter;
30
    }
31
32
    public function load(
33
        AggregateIdInterface $aggregateId,
34
        AggregateRevision $from = null,
35
        AggregateRevision $to = null
36
    ): StreamInterface {
37
        $commitSequence = $this->storageAdapter->load((string)$aggregateId, (string)$from, (string)$to);
38
39
        return Stream::fromNative([
40
            'aggregateId' => $aggregateId->toNative(),
41
            'commitSequence' => $commitSequence->toNative()
42
        ]);
43
    }
44
45
    public function append(StreamInterface $stream, Sequence $knownHead): StorageResultInterface
46
    {
47
        $commitSequence = $stream->getCommitRange($knownHead->increment(), $stream->getHeadSequence());
48
49
        try {
50
            /** @var CommitInterface $commit */
51
            foreach ($commitSequence as $commit) {
52
                $identifier = $stream->getAggregateId().'-'.(string)$commit->getSequence();
53
                $this->storageAdapter->append($identifier, $commit->toNative());
54
            }
55
        } catch (DocumentConflict $error) {
56
            return new StorageError;
57
        }
58
59
        return new StorageSuccess;
60
    }
61
}
62