|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Patchlevel\EventSourcing\DCB; |
| 6 | + |
| 7 | +use Patchlevel\EventSourcing\Message\Message; |
| 8 | +use Patchlevel\EventSourcing\Store\Header\TagsHeader; |
| 9 | + |
| 10 | +use function array_diff; |
| 11 | +use function array_map; |
| 12 | +use function array_merge; |
| 13 | +use function array_unique; |
| 14 | +use function array_values; |
| 15 | +use function in_array; |
| 16 | +use function sort; |
| 17 | + |
| 18 | +/** |
| 19 | + * @experimental |
| 20 | + * @extends Projection<array<string, mixed>> |
| 21 | + */ |
| 22 | +final class CompositeProjection extends Projection |
| 23 | +{ |
| 24 | + /** @param array<string, Projection> $projections */ |
| 25 | + public function __construct( |
| 26 | + private readonly array $projections, |
| 27 | + ) { |
| 28 | + } |
| 29 | + |
| 30 | + /** @return list<string> */ |
| 31 | + public function tagFilter(): array |
| 32 | + { |
| 33 | + $tags = []; |
| 34 | + |
| 35 | + foreach ($this->projections as $projection) { |
| 36 | + $tags = array_merge($tags, $projection->tagFilter()); |
| 37 | + } |
| 38 | + |
| 39 | + return array_values(array_unique($tags)); |
| 40 | + } |
| 41 | + |
| 42 | + /** @return list<list<string>> */ |
| 43 | + public function groupedTagFilter(): array |
| 44 | + { |
| 45 | + $result = []; |
| 46 | + |
| 47 | + foreach ($this->projections as $projection) { |
| 48 | + $tags = $projection->tagFilter(); |
| 49 | + |
| 50 | + sort($tags); |
| 51 | + |
| 52 | + if (in_array($tags, $result, true)) { |
| 53 | + continue; |
| 54 | + } |
| 55 | + |
| 56 | + $result[] = $tags; |
| 57 | + } |
| 58 | + |
| 59 | + return $result; |
| 60 | + } |
| 61 | + |
| 62 | + /** @return array<string, mixed> */ |
| 63 | + public function initialState(): array |
| 64 | + { |
| 65 | + return array_map(static function (Projection $projection) { |
| 66 | + return $projection->initialState(); |
| 67 | + }, $this->projections); |
| 68 | + } |
| 69 | + |
| 70 | + public function apply(mixed $state, Message $message): mixed |
| 71 | + { |
| 72 | + $tags = $message->header(TagsHeader::class)->tags; |
| 73 | + |
| 74 | + foreach ($this->projections as $name => $projection) { |
| 75 | + $neededTags = $projection->tagFilter(); |
| 76 | + |
| 77 | + if (!$this->isSubset($neededTags, $tags)) { |
| 78 | + continue; |
| 79 | + } |
| 80 | + |
| 81 | + $state[$name] = $projection->apply($state[$name], $message); |
| 82 | + } |
| 83 | + |
| 84 | + return $state; |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * @param list<string> $needle |
| 89 | + * @param list<string> $haystack |
| 90 | + */ |
| 91 | + private function isSubset(array $needle, array $haystack): bool |
| 92 | + { |
| 93 | + return empty(array_diff($needle, $haystack)); |
| 94 | + } |
| 95 | +} |
0 commit comments