From 8040d9c97ced5619179bd4e032b17a82904b5af4 Mon Sep 17 00:00:00 2001 From: Kevin Bond Date: Mon, 22 Jan 2024 18:47:31 -0500 Subject: [PATCH] feat(twig): make `ComponentAttributes` traversable/countable --- src/TwigComponent/CHANGELOG.md | 4 ++++ src/TwigComponent/src/ComponentAttributes.php | 12 +++++++++++- .../tests/Unit/ComponentAttributesTest.php | 8 ++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/TwigComponent/CHANGELOG.md b/src/TwigComponent/CHANGELOG.md index 716e0c555a..e924524ce1 100644 --- a/src/TwigComponent/CHANGELOG.md +++ b/src/TwigComponent/CHANGELOG.md @@ -1,5 +1,9 @@ # CHANGELOG +## Unreleased + +- Make `ComponentAttributes` traversable/countable. + ## 2.13.0 - [BC BREAK] Add component metadata to `PreMountEvent` and `PostMountEvent` diff --git a/src/TwigComponent/src/ComponentAttributes.php b/src/TwigComponent/src/ComponentAttributes.php index 408b2055fa..8606a1c83e 100644 --- a/src/TwigComponent/src/ComponentAttributes.php +++ b/src/TwigComponent/src/ComponentAttributes.php @@ -19,7 +19,7 @@ * * @immutable */ -final class ComponentAttributes +final class ComponentAttributes implements \IteratorAggregate, \Countable { /** * @param array $attributes @@ -157,4 +157,14 @@ public function remove($key): self return new self($attributes); } + + public function getIterator(): \Traversable + { + return new \ArrayIterator($this->attributes); + } + + public function count(): int + { + return \count($this->attributes); + } } diff --git a/src/TwigComponent/tests/Unit/ComponentAttributesTest.php b/src/TwigComponent/tests/Unit/ComponentAttributesTest.php index 32e7d312f8..35fcb5b7d7 100644 --- a/src/TwigComponent/tests/Unit/ComponentAttributesTest.php +++ b/src/TwigComponent/tests/Unit/ComponentAttributesTest.php @@ -191,4 +191,12 @@ public function testNullBehaviour(): void $this->assertSame(['disabled' => null], $attributes->all()); $this->assertSame(' disabled', (string) $attributes); } + + public function testIsTraversableAndCountable(): void + { + $attributes = new ComponentAttributes(['foo' => 'bar']); + + $this->assertSame($attributes->all(), iterator_to_array($attributes)); + $this->assertCount(1, $attributes); + } }