|
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
|
|
|
|