Esempio n. 1
0
 /**
  * <p><b>Syntax</b>: cycle (source)
  * <p>Cycles through the source sequence.
  * <p>Source keys are discarded.
  * @param array|\Iterator|\IteratorAggregate|Enumerable $source Source sequence.
  * @throws \InvalidArgumentException If source is not array or Traversible or Enumerable.
  * @throws \UnexpectedValueException If source contains no elements (checked during enumeration).
  * @return Enumerable Endless list of items repeating the source sequence.
  */
 public static function cycle($source)
 {
     $source = Enumerable::from($source);
     return new Enumerable(function () use($source) {
         $it = new \EmptyIterator();
         $i = 0;
         return new Enumerator(function ($yield) use($source, &$it, &$i) {
             /** @var $source Enumerable */
             /** @var $it \Iterator */
             if (!$it->valid()) {
                 $it = $source->getIterator();
                 $it->rewind();
                 if (!$it->valid()) {
                     throw new \UnexpectedValueException(Enumerable::ERROR_NO_ELEMENTS);
                 }
             }
             $yield($it->current(), $i++);
             $it->next();
             return true;
         });
     });
 }
<?php

$it = new EmptyIterator();
var_dump($it->valid());
$it->rewind();
var_dump($it->valid());
$it->next();
var_dump($it->valid());
try {
    var_dump($it->key());
} catch (BadMethodCallException $e) {
    echo $e->getMessage() . "\n";
}
try {
    var_dump($it->current());
} catch (BadMethodCallException $e) {
    echo $e->getMessage() . "\n";
}
var_dump($it->valid());
?>
===DONE===
 function next()
 {
     echo __METHOD__ . "\n";
     parent::next();
 }