Skip to content

Commit

Permalink
Minor update.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Aug 21, 2019
1 parent 913aa8c commit 2d2b6d9
Showing 1 changed file with 23 additions and 44 deletions.
67 changes: 23 additions & 44 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
use drupol\collection\Operation\Sort;
use drupol\collection\Operation\Walk;
use drupol\collection\Operation\Zip;
use Traversable;

/**
* Class Collection.
Expand Down Expand Up @@ -180,7 +179,11 @@ public function get($key, $default = null)
*/
public function getIterator()
{
return $this->makeIterator($this->source);
if ($this->source instanceof Closure) {
return ($this->source)();
}

return new ArrayIterator((array) $this->source);
}

/**
Expand Down Expand Up @@ -228,7 +231,7 @@ public function map(callable ...$callbacks): CollectionInterface
*/
public function merge(...$sources): CollectionInterface
{
return $this->run(Merge::with(\array_map([$this, 'makeIterator'], $sources)));
return $this->run(Merge::with($sources));
}

/**
Expand Down Expand Up @@ -391,11 +394,21 @@ public function walk(callable ...$callbacks): CollectionInterface
*/
public static function with($data): CollectionInterface
{
if ($data instanceof Closure || \is_callable($data)) {
if ($data instanceof Closure) {
return self::withClosure($data);
}

return self::withArray(self::getArrayableItems($data));
if ($data instanceof \Traversable) {
return self::withArray(
\iterator_to_array(
(static function () use ($data) {
yield from $data;
})()
)
);
}

return self::withArray((array) $data);
}

/**
Expand All @@ -406,52 +419,18 @@ public function zip(...$items): CollectionInterface
return $this->run(Zip::with($items));
}

/**
* Get items as an array.
*
* @param mixed $items
*
* @return array
*/
private static function getArrayableItems($items): array
{
if (\is_array($items)) {
return $items;
}

if ($items instanceof Traversable) {
return \iterator_to_array($items);
}

return (array) $items;
}

/**
* Make an iterator from the given source.
*
* @param mixed $source
*
* @return \Iterator
*/
private function makeIterator($source): \Iterator
{
if (\is_callable($source)) {
return $source();
}

return new ArrayIterator((array) $source);
}

/**
* @param array $data
*
* @return \drupol\collection\Contract\Collection
*/
private static function withArray(array $data): CollectionInterface
{
return self::withClosure(static function () use ($data) {
yield from $data;
});
return self::withClosure(
static function () use ($data) {
yield from $data;
}
);
}

/**
Expand Down

0 comments on commit 2d2b6d9

Please sign in to comment.