more uses of iterator in PHP

This commit is contained in:
Trismegiste 2013-05-11 22:37:20 +02:00
parent 8120aae5a7
commit 3695a15150

View File

@ -14,11 +14,11 @@ use DesignPatterns\Iterator\CardGame;
class IteratorTest extends \PHPUnit_Framework_TestCase class IteratorTest extends \PHPUnit_Framework_TestCase
{ {
protected $game; protected $deck;
protected function setUp() protected function setUp()
{ {
$this->game = new CardGame(); $this->deck = new CardGame();
} }
/** /**
@ -29,7 +29,7 @@ class IteratorTest extends \PHPUnit_Framework_TestCase
public function testCardinal() public function testCardinal()
{ {
$counter = 0; $counter = 0;
foreach ($this->game as $key => $card) { foreach ($this->deck as $key => $card) {
$counter++; $counter++;
} }
@ -42,13 +42,27 @@ class IteratorTest extends \PHPUnit_Framework_TestCase
public function testExampleOf_PHP_Helper() public function testExampleOf_PHP_Helper()
{ {
// PHPUnit works on array or iterator : // PHPUnit works on array or iterator :
$this->assertCount(32, $this->game); $this->assertCount(32, $this->deck);
// a easy way to get an array from interator : // a easy way to get an array from interator :
$cards = iterator_to_array($this->game); $cards = iterator_to_array($this->deck);
$this->assertEquals('A of S', $cards['SA']); $this->assertEquals('A of S', $cards['SA']);
// a easy way to get an iterator from an array : // a easy way to get an iterator from an array :
$iterator = new \ArrayIterator($cards); $iterator = new \ArrayIterator($cards);
$this->assertInstanceOf('\Iterator', $iterator); $this->assertInstanceOf('\Iterator', $iterator);
} }
/**
* Iterator can be combine, chained, filter, there are many in the SPL
* and sadly they are rarely used.
*/
public function testIteratorCombining()
{
// a fancy way to add a joker to the deck :
$joker = array('JK' => 'Joker');
$newDeck = new \AppendIterator();
$newDeck->append($this->deck);
$newDeck->append(new \ArrayIterator($joker));
$this->assertCount(33, $newDeck);
}
} }