|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * This file is part of Storyblok-Api. |
| 7 | + * |
| 8 | + * (c) SensioLabs Deutschland <[email protected]> |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view the LICENSE |
| 11 | + * file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Storyblok\Api\Domain\Value\Resolver; |
| 15 | + |
| 16 | +/** |
| 17 | + * @author Silas Joisten <[email protected]> |
| 18 | + * |
| 19 | + * @implements \IteratorAggregate<int, Relation> |
| 20 | + */ |
| 21 | +final class RelationCollection implements \Countable, \IteratorAggregate |
| 22 | +{ |
| 23 | + /** |
| 24 | + * @var list<Relation> |
| 25 | + */ |
| 26 | + private array $items = []; |
| 27 | + |
| 28 | + /** |
| 29 | + * @param list<Relation> $items |
| 30 | + */ |
| 31 | + public function __construct( |
| 32 | + array $items = [], |
| 33 | + ) { |
| 34 | + foreach ($items as $item) { |
| 35 | + $this->add($item); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * @return \Traversable<int, Relation> |
| 41 | + */ |
| 42 | + public function getIterator(): \Traversable |
| 43 | + { |
| 44 | + return new \ArrayIterator($this->items); |
| 45 | + } |
| 46 | + |
| 47 | + public function count(): int |
| 48 | + { |
| 49 | + return \count($this->items); |
| 50 | + } |
| 51 | + |
| 52 | + public function add(Relation $relation): void |
| 53 | + { |
| 54 | + if ($this->has($relation)) { |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + $this->items[] = $relation; |
| 59 | + } |
| 60 | + |
| 61 | + public function has(Relation $relation): bool |
| 62 | + { |
| 63 | + foreach ($this->items as $item) { |
| 64 | + if ($item->value === $relation->value) { |
| 65 | + return true; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return false; |
| 70 | + } |
| 71 | + |
| 72 | + public function remove(Relation $relation): void |
| 73 | + { |
| 74 | + foreach ($this->items as $key => $item) { |
| 75 | + if ($item->value === $relation->value) { |
| 76 | + unset($this->items[$key]); |
| 77 | + |
| 78 | + break; |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + public function toString(): string |
| 84 | + { |
| 85 | + return implode(',', array_map(static fn (Relation $relation): string => $relation->value, $this->items)); |
| 86 | + } |
| 87 | +} |
0 commit comments