<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Stream;


class IterableStream extends AbstractStream
{
  
  protected $it;

  
  public function __construct(iterable $it)
  {
    $this->it = $it;
  }

  public function isValid(): bool
  {
    return !\is_null($this->it);
  }

  public function toArray(): array
  {
    $this->assertValid();
    $result = ($this->it instanceof \Traversable) ? \iterator_to_array($this->it) : ((array)$this->it);
    $this->invalidate();

    return $result;
  }

  public function toIterator(): iterable
  {
    $this->assertValid();
    $result = $this->it;
    $this->invalidate();

    if (\is_array($result)) {
      $result = (new \ArrayObject($result))->getIterator();
    }

    return $result;
  }

  protected function invalidate(): void
  {
    $this->it = null;
  }

  public static function emptyStream(): IterableStream
  {
    $fn = static function() {
      if (false) {
        yield null;
      }
    };

    return new IterableStream($fn());
  }
}