Skip to content

Commit

Permalink
Fix Scroll:current() annotation
Browse files Browse the repository at this point in the history
Calling Scroll->current() on an invalid Iterator should be avoided: the Iterator documentation
states that code should first call "valid()" before accessing the "current()" value. Not
doing so can lead to unexpected results.

Scroll will throw an InvalidException when trying to call "current()" on an invalid state.
  • Loading branch information
thePanz committed Jan 20, 2020
1 parent f209099 commit 6236a07
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Backward Compatibility Breaks
### Added
### Changed
- Scroll is now throwing an exception when calling `current()` on an invalid iteration: always call `valid()` before
accessing the current item, as documented in PHP's Iterator documentation [#1749](https://github.com/ruflin/Elastica/pull/1749)

### Deprecated
### Removed
### Fixed
Expand Down
13 changes: 8 additions & 5 deletions lib/Elastica/Scroll.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Elastica;

use Elastica\Exception\InvalidException;

/**
* Scroll Iterator.
*
Expand Down Expand Up @@ -43,9 +45,6 @@ class Scroll implements \Iterator
private $totalPages = 0;
private $currentPage = 0;

/**
* Constructor.
*/
public function __construct(Search $search, string $expiryTime = '1m')
{
$this->_search = $search;
Expand All @@ -57,8 +56,12 @@ public function __construct(Search $search, string $expiryTime = '1m')
*
* @see http://php.net/manual/en/iterator.current.php
*/
public function current(): ?ResultSet
public function current(): ResultSet
{
if (!$this->_currentResultSet) {
throw new InvalidException('Could not fetch the current ResultSet from an invalid iterator. Did you forget to call "valid()"?');
}

return $this->_currentResultSet;
}

Expand All @@ -67,7 +70,7 @@ public function current(): ?ResultSet
*
* @see http://php.net/manual/en/iterator.next.php
*/
public function next()
public function next(): void
{
$this->_currentResultSet = null;
if ($this->currentPage < $this->totalPages) {
Expand Down

0 comments on commit 6236a07

Please sign in to comment.