|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Cone\Root\Fields; |
| 6 | + |
| 7 | +use Closure; |
| 8 | +use Cone\Root\Traits\HasAttributes; |
| 9 | +use Cone\Root\Traits\Makeable; |
| 10 | +use Illuminate\Contracts\Support\Arrayable; |
| 11 | +use Illuminate\Support\Traits\Conditionable; |
| 12 | +use JsonSerializable; |
| 13 | + |
| 14 | +class OptGroup implements Arrayable, JsonSerializable |
| 15 | +{ |
| 16 | + use Conditionable; |
| 17 | + use HasAttributes; |
| 18 | + use Makeable; |
| 19 | + |
| 20 | + /** |
| 21 | + * The options within the opt group. |
| 22 | + * |
| 23 | + * @var list<Option> |
| 24 | + */ |
| 25 | + protected array $options = []; |
| 26 | + |
| 27 | + /** |
| 28 | + * Create a new opt group instance. |
| 29 | + */ |
| 30 | + public function __construct(protected string $label, array $options) |
| 31 | + { |
| 32 | + $this->options = array_map(function (Option|int|string $item, int|string $key): Option { |
| 33 | + return match (true) { |
| 34 | + $item instanceof Option => $item, |
| 35 | + default => new Option((string) $key, (string) $item), |
| 36 | + }; |
| 37 | + }, $options, array_keys($options)); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Set the "disabled" HTML attribute. |
| 42 | + */ |
| 43 | + public function disabled(bool $value = true): static |
| 44 | + { |
| 45 | + return $this->setAttribute('disabled', $value); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Set the "selected" HTML attribute. |
| 50 | + */ |
| 51 | + public function selected(bool|Closure $value = true): static |
| 52 | + { |
| 53 | + foreach ($this->options as $option) { |
| 54 | + $option->selected($value); |
| 55 | + } |
| 56 | + |
| 57 | + return $this; |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Convert the element to a JSON serializable format. |
| 62 | + */ |
| 63 | + public function jsonSerialize(): array |
| 64 | + { |
| 65 | + return $this->toArray(); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Get the array representation of the object. |
| 70 | + */ |
| 71 | + public function toArray(): array |
| 72 | + { |
| 73 | + return [ |
| 74 | + 'attrs' => $this->newAttributeBag(), |
| 75 | + 'label' => $this->label, |
| 76 | + 'options' => array_map(fn (Option $option): array => $option->toArray(), $this->options), |
| 77 | + ]; |
| 78 | + } |
| 79 | +} |
0 commit comments