You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.5 KiB
66 lines
1.5 KiB
<?php
|
|
|
|
namespace libs;
|
|
|
|
class LazyCollection implements \IteratorAggregate
|
|
{
|
|
protected $source;
|
|
|
|
public function __construct($source = null)
|
|
{
|
|
if ($source instanceof \Closure || $source instanceof self) {
|
|
$this->source = $source;
|
|
} elseif (is_null($source)) {
|
|
$this->source = static::empty();
|
|
} else {
|
|
$this->source = $this->getArrayableItems($source);
|
|
}
|
|
}
|
|
|
|
public function getIterator(): \Traversable
|
|
{
|
|
return $this->makeIterator($this->source);
|
|
}
|
|
|
|
protected function makeIterator($source)
|
|
{
|
|
if ($source instanceof \Closure) {
|
|
$source = $source();
|
|
}
|
|
|
|
if (is_array($source)) {
|
|
return new \ArrayIterator($source);
|
|
}
|
|
|
|
return $source;
|
|
}
|
|
|
|
public static function make($source = null)
|
|
{
|
|
return new static($source instanceof \Closure ? $source() : $source);
|
|
}
|
|
|
|
public function each(callable $callback)
|
|
{
|
|
foreach ($this->getIterator() as $key => $value) {
|
|
if ($callback($value, $key) === false) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
return $this;
|
|
}
|
|
|
|
protected function getArrayableItems($items)
|
|
{
|
|
if (is_array($items)) {
|
|
return $items;
|
|
} elseif ($items instanceof \Traversable) {
|
|
return iterator_to_array($items);
|
|
} elseif (is_object($items) && method_exists($items, 'toArray')) {
|
|
return $items->toArray();
|
|
}
|
|
|
|
return (array) $items;
|
|
}
|
|
}
|
|
|