| 1 | <?php |
||
| 6 | class Collection implements CollectionInterface |
||
| 7 | { |
||
| 8 | protected array $items = []; |
||
|
|
|||
| 9 | |||
| 10 | public function addItem(string $name, mixed $item, int $priority = 50): static |
||
| 11 | { |
||
| 12 | if ($this->has($name)) { |
||
| 13 | throw new DuplicateKeyException('Item with name '.$name.' already defined'); |
||
| 14 | } |
||
| 15 | |||
| 16 | $this->items[$priority][$name] = $item; |
||
| 17 | return $this; |
||
| 18 | } |
||
| 19 | |||
| 20 | 8 | public function removeItem(string $name, int $priority = null): static |
|
| 21 | { |
||
| 22 | 8 | if ($priority === null) { |
|
| 23 | 1 | return $this->removeItemWithoutPriority($name); |
|
| 24 | } |
||
| 25 | |||
| 26 | 8 | if ($this->items[$priority][$name] ?? false) { |
|
| 27 | 8 | unset($this->items[$priority][$name]); |
|
| 28 | } |
||
| 29 | |||
| 30 | return $this; |
||
| 31 | } |
||
| 32 | |||
| 33 | protected function removeItemWithoutPriority(string $name): static |
||
| 34 | { |
||
| 35 | foreach ($this->items as $priority => $items) { |
||
| 36 | 2 | if ($items[$name] ?? false) { |
|
| 37 | unset($this->items[$priority][$name]); |
||
| 38 | 2 | } |
|
| 39 | 1 | } |
|
| 40 | 1 | ||
| 41 | return $this; |
||
| 42 | } |
||
| 43 | 1 | ||
| 44 | public function has(string $name): bool |
||
| 45 | { |
||
| 46 | 1 | foreach ($this->items as $items) { |
|
| 47 | if ($items[$name] ?? false) { |
||
| 48 | return true; |
||
| 49 | } |
||
| 50 | } |
||
| 51 | |||
| 52 | return false; |
||
| 53 | } |
||
| 54 | 1 | ||
| 55 | /** |
||
| 56 | 1 | * @param bool $sort |
|
| 57 | 1 | * @return array[] |
|
| 58 | 1 | */ |
|
| 59 | public function getItems(bool $sort = true): array |
||
| 60 | { |
||
| 61 | $items = $this->items; |
||
| 62 | 1 | ||
| 63 | if ($sort) { |
||
| 64 | krsort($items, SORT_NUMERIC); |
||
| 65 | 8 | } |
|
| 66 | |||
| 67 | 8 | return $items; |
|
| 68 | 3 | } |
|
| 69 | 3 | ||
| 70 | public function getFlatItems(bool $sort = true): array |
||
| 71 | { |
||
| 72 | $flatItems = []; |
||
| 73 | 8 | ||
| 74 | foreach ($this->getItems($sort) as $items) { |
||
| 75 | foreach ($items as $name => $item) { |
||
| 76 | $flatItems[$name] = $item; |
||
| 77 | } |
||
| 78 | } |
||
| 79 | |||
| 80 | 7 | return $flatItems; |
|
| 81 | } |
||
| 82 | 7 | ||
| 83 | /** |
||
| 84 | 7 | * @return $this |
|
| 85 | 7 | */ |
|
| 86 | public function flush(): static |
||
| 87 | { |
||
| 88 | 7 | $this->items = []; |
|
| 89 | return $this; |
||
| 90 | } |
||
| 91 | } |
||
| 92 |