diff --git a/src/Properties.php b/src/Properties.php index 1381b26..5726af3 100644 --- a/src/Properties.php +++ b/src/Properties.php @@ -3,6 +3,7 @@ namespace ipl\Stdlib; use OutOfBoundsException; +use Traversable; /** * Trait for property access, mutation and array access. @@ -83,6 +84,18 @@ protected function setProperty($key, $value) return $this; } + /** + * Iterate over all existing properties + * + * @return Traversable + */ + public function getIterator(): Traversable + { + foreach ($this->properties as $key => $value) { + yield $key => $value; + } + } + /** * Check whether an offset exists * diff --git a/tests/PropertiesTest.php b/tests/PropertiesTest.php index 4c044cf..2af9fed 100644 --- a/tests/PropertiesTest.php +++ b/tests/PropertiesTest.php @@ -96,6 +96,28 @@ public function testUnsetForPropertyAccess() $subject->foo; } + public function testPropertyIterationWorks() + { + $subject = new TestClassUsingThePropertiesTrait(); + $subject->foo = 'bar'; + $subject->bar = 'foo'; + + $i = 0; + foreach ($subject as $name => $value) { + if ($i === 0) { + $this->assertEquals($name, 'foo'); + $this->assertEquals($value, 'bar'); + } elseif ($i === 1) { + $this->assertEquals($name, 'bar'); + $this->assertEquals($value, 'foo'); + } else { + $this->fail('There are more properties iterable than defined'); + } + + $i++; + } + } + public function testGetPropertiesReturnsEmptyArrayIfUnset() { $this->markTestSkipped('Properties::getProperties() not yet implemented'); diff --git a/tests/TestClassUsingThePropertiesTrait.php b/tests/TestClassUsingThePropertiesTrait.php index 7d5a41e..a4c9afd 100644 --- a/tests/TestClassUsingThePropertiesTrait.php +++ b/tests/TestClassUsingThePropertiesTrait.php @@ -4,7 +4,7 @@ use ipl\Stdlib\Properties; -class TestClassUsingThePropertiesTrait implements \ArrayAccess +class TestClassUsingThePropertiesTrait implements \ArrayAccess, \IteratorAggregate { use Properties; }