diff --git a/Iterator/CardGame.php b/Iterator/CardGame.php new file mode 100644 index 0000000..c4b3898 --- /dev/null +++ b/Iterator/CardGame.php @@ -0,0 +1,80 @@ +number) . ' of ' . current($this->color); + } + + /** + * Return the current key + */ + public function key() + { + return current($this->color) . current($this->number); + } + + /** + * Go to the next item in the collection + */ + public function next() + { + if (false === next($this->number)) { + if (false !== next($this->color)) { + reset($this->number); + } + } + } + + /** + * Go to the first item in the collection + */ + public function rewind() + { + reset($this->color); + reset($this->number); + } + + /** + * Is the current position a valid item (true) + * or do we reach the end (false) ? + */ + public function valid() + { + return current($this->number) || current($this->color); + } + +} \ No newline at end of file diff --git a/Iterator/Iterator.php b/Iterator/Iterator.php index d27adae..753ce77 100644 --- a/Iterator/Iterator.php +++ b/Iterator/Iterator.php @@ -32,6 +32,8 @@ class File public function process() { + // this is the place to show how using an iterator, with foreach + // See the CardGame.php file $this->_rowset->process(); } } @@ -55,6 +57,14 @@ class Rowset implements Iterator public function process() { // this actually calls rewind(), { next(), valid(), key() and current() :} + /** + * THE key feature of the Iterator Pattern is to provide a *public contract* + * to iterate on a collection without knowing how items are handled inside + * the collection. It is not just an easy way to use "foreach" + * + * One cannot see the point of iterator pattern if you iterate on $this. + * This example is unclear and mixed with some Composite pattern ideas. + */ foreach ($this as $line => $row) { $row->process(); } diff --git a/Tests/Iterator/IteratorTest.php b/Tests/Iterator/IteratorTest.php new file mode 100644 index 0000000..6b9fd12 --- /dev/null +++ b/Tests/Iterator/IteratorTest.php @@ -0,0 +1,56 @@ +game = new CardGame(); + } + + /** + * This is the client of the iterator. + * It remains unchanged even if one I decide to use MongoDB to store the + * card. + */ + public function testCardinal() + { + $counter = 0; + foreach ($this->game as $key => $card) { + $counter++; + } + + $this->assertEquals(32, $counter); + } + + /** + * Some fancy functions of PHP. + */ + public function testExampleOf_PHP_Helper() + { + // PHPUnit works on array or iterator : + $this->assertCount(32, $this->game); + // a easy way to get an array from interator : + $cards = iterator_to_array($this->game); + $this->assertEquals('A of S', $cards['SA']); + // a easy way to get an iterator from an array : + $iterator = new \ArrayIterator($cards); + $this->assertInstanceOf('\Iterator', $iterator); + } + +} \ No newline at end of file