Skip to content

Commit

Permalink
Properties: Implement iteration support
Browse files Browse the repository at this point in the history
  • Loading branch information
nilmerg committed May 23, 2022
1 parent af55822 commit f7b04a8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
13 changes: 13 additions & 0 deletions src/Properties.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace ipl\Stdlib;

use OutOfBoundsException;
use Traversable;

/**
* Trait for property access, mutation and array access.
Expand Down Expand Up @@ -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
*
Expand Down
22 changes: 22 additions & 0 deletions tests/PropertiesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
2 changes: 1 addition & 1 deletion tests/TestClassUsingThePropertiesTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use ipl\Stdlib\Properties;

class TestClassUsingThePropertiesTrait implements \ArrayAccess
class TestClassUsingThePropertiesTrait implements \ArrayAccess, \IteratorAggregate
{
use Properties;
}

0 comments on commit f7b04a8

Please sign in to comment.