|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace EventEngine\DocumentStore\Postgres\Metadata; |
| 5 | + |
| 6 | +use EventEngine\DocumentStore\Index; |
| 7 | +use EventEngine\DocumentStore\Postgres\Exception\InvalidArgumentException; |
| 8 | + |
| 9 | +final class MetadataColumnIndex implements Index |
| 10 | +{ |
| 11 | + /** |
| 12 | + * @var Column[] |
| 13 | + */ |
| 14 | + private $columns; |
| 15 | + |
| 16 | + /** |
| 17 | + * @var Index |
| 18 | + */ |
| 19 | + private $indexCmd; |
| 20 | + |
| 21 | + public static function fromArray(array $data): Index |
| 22 | + { |
| 23 | + if(!array_key_exists('column', $data)) { |
| 24 | + throw new InvalidArgumentException('Missing key columns in index data'); |
| 25 | + } |
| 26 | + |
| 27 | + if(!array_key_exists('index', $data)) { |
| 28 | + throw new InvalidArgumentException('Missing key index in data'); |
| 29 | + } |
| 30 | + |
| 31 | + if(!array_key_exists('indexClass', $data)) { |
| 32 | + throw new InvalidArgumentException('Missing key indexClass in data'); |
| 33 | + } |
| 34 | + |
| 35 | + $indexClass = $data['indexClass']; |
| 36 | + $index = $indexClass::fromArray($data['index']); |
| 37 | + |
| 38 | + return new self($index, ...array_map(function (string $columnSql) { |
| 39 | + return new Column($columnSql); |
| 40 | + }, $data['columns'])); |
| 41 | + } |
| 42 | + |
| 43 | + public function __construct(Index $indexCmd, Column ...$columns) |
| 44 | + { |
| 45 | + $this->columns = $columns; |
| 46 | + $this->indexCmd = $indexCmd; |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * @return Column[] |
| 51 | + */ |
| 52 | + public function columns(): array |
| 53 | + { |
| 54 | + return $this->columns; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * @return Index |
| 59 | + */ |
| 60 | + public function indexCmd(): Index |
| 61 | + { |
| 62 | + return $this->indexCmd; |
| 63 | + } |
| 64 | + |
| 65 | + public function toArray() |
| 66 | + { |
| 67 | + return [ |
| 68 | + 'columns' => array_map(function (Column $column) { |
| 69 | + return $column->sql(); |
| 70 | + }, $this->columns), |
| 71 | + 'index' => $this->indexCmd->toArray(), |
| 72 | + 'indexClass' => get_class($this->indexCmd), |
| 73 | + ]; |
| 74 | + } |
| 75 | +} |
0 commit comments