Skip to content

Commit

Permalink
CachingIterator: do not ask when not in valid state (#230)
Browse files Browse the repository at this point in the history
  • Loading branch information
hrach authored and dg committed Nov 11, 2020
1 parent e1272a1 commit d73ea8e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/Latte/Runtime/CachingIterator.php
Expand Up @@ -156,22 +156,24 @@ public function rewind(): void


/**
* Returns the next key.
* Returns the next key or null if position is not valid.
* @return mixed
*/
public function getNextKey()
{
return $this->getInnerIterator()->key();
$iterator = $this->getInnerIterator();
return $iterator->valid() ? $iterator->key() : null;
}


/**
* Returns the next element.
* Returns the next element or null if position is not valid.
* @return mixed
*/
public function getNextValue()
{
return $this->getInnerIterator()->current();
$iterator = $this->getInnerIterator();
return $iterator->valid() ? $iterator->current() : null;
}


Expand Down
37 changes: 37 additions & 0 deletions tests/Latte/CachingIterator.basic.phpt
Expand Up @@ -73,3 +73,40 @@ test('', function () {
Assert::same(0, $iterator->getCounter());
Assert::true($iterator->isEmpty());
});

test('Check if next position is valid', function () {
// empty iterator
$inner = new class implements Iterator {
public function current()
{
throw new RuntimeException('Invalid state');
}


public function next(): void
{
}


public function key()
{
throw new RuntimeException('Invalid state');
}


public function valid(): bool
{
return false;
}


public function rewind(): void
{
}
};

$iterator = new CachingIterator($inner);
$iterator->rewind();
Assert::null($iterator->nextKey);
Assert::null($iterator->nextValue);
});

0 comments on commit d73ea8e

Please sign in to comment.