|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\UX\TwigComponent; |
| 13 | + |
| 14 | +/** |
| 15 | + * @author Kevin Bond <[email protected]> |
| 16 | + * |
| 17 | + * @experimental |
| 18 | + */ |
| 19 | +final class AttributeBag |
| 20 | +{ |
| 21 | + /** |
| 22 | + * @param array<string, string> $attributes |
| 23 | + */ |
| 24 | + public function __construct(public array $attributes) |
| 25 | + { |
| 26 | + } |
| 27 | + |
| 28 | + public static function create(array|self $attributes): self |
| 29 | + { |
| 30 | + return $attributes instanceof self ? $attributes : new self($attributes); |
| 31 | + } |
| 32 | + |
| 33 | + public function __toString(): string |
| 34 | + { |
| 35 | + return \array_reduce( |
| 36 | + \array_keys($this->attributes), |
| 37 | + fn(string $carry, string $key) => \sprintf('%s %s="%s"', $carry, $key, $this->attributes[$key]), |
| 38 | + '' |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + public function prepend(array $with): self |
| 43 | + { |
| 44 | + foreach ($this->attributes as $key => $value) { |
| 45 | + $with[$key] = isset($with[$key]) ? "{$with[$key]} {$value}" : $value; |
| 46 | + } |
| 47 | + |
| 48 | + return new self($with); |
| 49 | + } |
| 50 | + |
| 51 | + public function append(array $with): self |
| 52 | + { |
| 53 | + foreach ($this->attributes as $key => $value) { |
| 54 | + $with[$key] = isset($with[$key]) ? "{$value} {$with[$key]}" : $value; |
| 55 | + } |
| 56 | + |
| 57 | + return new self($with); |
| 58 | + } |
| 59 | + |
| 60 | + public function only(string ...$keys): self |
| 61 | + { |
| 62 | + $attributes = []; |
| 63 | + |
| 64 | + foreach ($this->attributes as $key => $value) { |
| 65 | + if (in_array($key, $keys, true)) { |
| 66 | + $attributes[$key] = $value; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return new self($attributes); |
| 71 | + } |
| 72 | + |
| 73 | + public function reject(string ...$keys): self |
| 74 | + { |
| 75 | + $clone = clone $this; |
| 76 | + |
| 77 | + foreach ($keys as $key) { |
| 78 | + unset($clone->attributes[$key]); |
| 79 | + } |
| 80 | + |
| 81 | + return $clone; |
| 82 | + } |
| 83 | +} |
0 commit comments