|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Tempest\View; |
| 6 | + |
| 7 | +use ArrayAccess; |
| 8 | +use ArrayIterator; |
| 9 | +use BadMethodCallException; |
| 10 | +use Countable; |
| 11 | +use IteratorAggregate; |
| 12 | +use JsonSerializable; |
| 13 | + |
| 14 | +final class ViewComponentParameters implements ArrayAccess, IteratorAggregate, Countable, JsonSerializable |
| 15 | +{ |
| 16 | + /** @var ViewComponentParameter[] */ |
| 17 | + private readonly array $parameters; |
| 18 | + |
| 19 | + public function __construct(ViewComponentParameter ...$parameters) |
| 20 | + { |
| 21 | + $this->parameters = $parameters; |
| 22 | + } |
| 23 | + |
| 24 | + /** @var ViewComponentParameter[] */ |
| 25 | + public array $required { |
| 26 | + get => array_filter($this->parameters, static fn (ViewComponentParameter $parameter) => $parameter->required); |
| 27 | + } |
| 28 | + |
| 29 | + /** @var ViewComponentParameter[] */ |
| 30 | + public array $optional { |
| 31 | + get => array_filter($this->parameters, static fn (ViewComponentParameter $parameter) => ! $parameter->required); |
| 32 | + } |
| 33 | + |
| 34 | + public function offsetExists(mixed $offset): bool |
| 35 | + { |
| 36 | + return isset($this->parameters[$offset]); |
| 37 | + } |
| 38 | + |
| 39 | + public function offsetGet(mixed $offset): ?ViewComponentParameter |
| 40 | + { |
| 41 | + return $this->parameters[$offset] ?? null; |
| 42 | + } |
| 43 | + |
| 44 | + public function offsetSet(mixed $offset, mixed $value): void |
| 45 | + { |
| 46 | + throw new BadMethodCallException('ViewComponentParameters is readonly'); |
| 47 | + } |
| 48 | + |
| 49 | + public function offsetUnset(mixed $offset): void |
| 50 | + { |
| 51 | + throw new BadMethodCallException('ViewComponentParameters is readonly'); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @return ArrayIterator<ViewComponentParameter> |
| 56 | + */ |
| 57 | + public function getIterator(): ArrayIterator |
| 58 | + { |
| 59 | + return new ArrayIterator($this->parameters); |
| 60 | + } |
| 61 | + |
| 62 | + public function count(): int |
| 63 | + { |
| 64 | + return count($this->parameters); |
| 65 | + } |
| 66 | + |
| 67 | + /** @return ViewComponentParameter[] */ |
| 68 | + public function toArray(): array |
| 69 | + { |
| 70 | + return $this->parameters; |
| 71 | + } |
| 72 | + |
| 73 | + public function getByName(string $name): ?ViewComponentParameter |
| 74 | + { |
| 75 | + return array_find($this->parameters, static fn (ViewComponentParameter $parameter) => $parameter->name === $name); |
| 76 | + } |
| 77 | + |
| 78 | + public function hasParameter(string $name): bool |
| 79 | + { |
| 80 | + return $this->getByName($name) !== null; |
| 81 | + } |
| 82 | + |
| 83 | + public function jsonSerialize(): array |
| 84 | + { |
| 85 | + return $this->parameters; |
| 86 | + } |
| 87 | +} |
0 commit comments