Created
February 20, 2019 06:52
-
-
Save ppshobi/5d4da801fac3be866ea617a5d9637cca to your computer and use it in GitHub Desktop.
CircularIterator - An InfininIteIterator for PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Iterator; | |
class CircularIterator implements Iterator | |
{ | |
private $entries; | |
public function __construct($entries) | |
{ | |
$this->entries = $entries; | |
$this->rewind(); | |
} | |
/** | |
* Return the current element | |
* @link http://php.net/manual/en/iterator.current.php | |
* @return mixed Can return any type. | |
* @since 5.0.0 | |
*/ | |
public function current() | |
{ | |
return current($this->entries); | |
} | |
/** | |
* Move forward to next element | |
* @link http://php.net/manual/en/iterator.next.php | |
* @return void Any returned value is ignored. | |
* @since 5.0.0 | |
*/ | |
public function next() | |
{ | |
next($this->entries); | |
if (!$this->current()) { | |
$this->rewind(); | |
} | |
} | |
/** | |
* Move backward to previous element | |
* @return void Any returned value is ignored. | |
* @since 5.0.0 | |
*/ | |
public function prev() | |
{ | |
prev($this->entries); | |
if (!$this->current()) { | |
$this->end(); | |
} | |
} | |
/** | |
* Return the key of the current element | |
* @link http://php.net/manual/en/iterator.key.php | |
* @return mixed scalar on success, or null on failure. | |
* @since 5.0.0 | |
*/ | |
public function key() | |
{ | |
return key($this->entries); | |
} | |
/** | |
* Checks if current position is valid | |
* @link http://php.net/manual/en/iterator.valid.php | |
* @return boolean The return value will be casted to boolean and then evaluated. | |
* Returns true on success or false on failure. | |
* @since 5.0.0 | |
*/ | |
public function valid() | |
{ | |
return true; | |
} | |
/** | |
* Rewind the Iterator to the first element | |
* @link http://php.net/manual/en/iterator.rewind.php | |
* @return void Any returned value is ignored. | |
* @since 5.0.0 | |
*/ | |
public function rewind() | |
{ | |
reset($this->entries); | |
} | |
/** | |
* Rewind the Iterator to the last element | |
* @link http://php.net/manual/en/iterator.rewind.php | |
* @return void Any returned value is ignored. | |
* @since 5.0.0 | |
*/ | |
public function end() | |
{ | |
end($this->entries); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This class implements the
Iterator
Interface and the behaviour looks like an InfiniteIterator. The main difference is that it supportsnext
andprev
functions so that you can move the array pointer manually. where from InfiniteIterator you can get only next item. In my case, I had to get the previous and next player from the loop.usage: