1 | <?php |
||
18 | final class CommitSequence implements IteratorAggregate, Countable |
||
19 | { |
||
20 | /** @var Vector */ |
||
21 | private $compositeVector; |
||
22 | |||
23 | public static function fromArray(array $commitsArray): CommitSequence |
||
29 | |||
30 | 1 | public static function makeEmpty(): CommitSequence |
|
31 | { |
||
32 | 1 | return new self; |
|
33 | } |
||
34 | |||
35 | 2 | public function __construct(array $commits = []) |
|
41 | |||
42 | public function push(CommitInterface $commit): self |
||
43 | { |
||
44 | if (!$this->isEmpty()) { |
||
45 | $nextRevision = $this->getHead()->getAggregateRevision()->increment(); |
||
46 | if (!$nextRevision->equals($commit->getAggregateRevision())) { |
||
47 | throw new \Exception(sprintf( |
||
48 | "Trying to add unexpected revision %s to event-sequence. Expected revision is $nextRevision", |
||
49 | $commit->getAggregateRevision() |
||
50 | )); |
||
51 | } |
||
52 | } |
||
53 | $commitSequence = clone $this; |
||
54 | $commitSequence->compositeVector->push($commit); |
||
55 | return $commitSequence; |
||
56 | } |
||
57 | |||
58 | public function toNative(): array |
||
66 | |||
67 | public function getTail(): ?CommitInterface |
||
71 | |||
72 | public function getHead(): ?CommitInterface |
||
73 | { |
||
74 | return $this->isEmpty() ? null : $this->compositeVector->last(); |
||
75 | } |
||
76 | |||
77 | public function get(StreamRevision $streamRevision): ?CommitInterface |
||
84 | |||
85 | public function getSlice(StreamRevision $start, StreamRevision $end): self |
||
86 | { |
||
87 | return $this->compositeVector->reduce( |
||
88 | function (CommitSequence $commits, CommitInterface $commit) use ($start, $end): CommitSequence { |
||
89 | if ($commit->getStreamRevision()->isWithinRange($start, $end)) { |
||
90 | $commits = $commits->push($commit); /* @var CommitSequence $commits */ |
||
91 | return $commits; |
||
92 | } |
||
93 | return $commits; |
||
94 | }, |
||
95 | new static |
||
96 | ); |
||
97 | } |
||
98 | |||
99 | public function isEmpty(): bool |
||
100 | { |
||
101 | return $this->compositeVector->isEmpty(); |
||
102 | } |
||
103 | |||
104 | public function revisionOf(CommitInterface $commit): StreamRevision |
||
108 | |||
109 | public function getLength(): int |
||
110 | { |
||
111 | return $this->count(); |
||
112 | } |
||
113 | |||
114 | public function count(): int |
||
115 | { |
||
116 | return $this->compositeVector->count(); |
||
117 | } |
||
118 | |||
119 | 2 | public function getIterator(): Iterator |
|
123 | |||
124 | private function __clone() |
||
125 | { |
||
126 | $this->compositeVector = clone $this->compositeVector; |
||
127 | } |
||
128 | } |
||
129 |