Skip to content
Permalink
Browse files

refactor: "small" refactor how to use iterators.

  • Loading branch information...
tarlepp committed Oct 15, 2019
1 parent e9641c4 commit d8d02474db966e1fabdee9a1ebf8f877a575a246
Showing with 16 additions and 23 deletions.
  1. +16 −23 src/Collection/CollectionTrait.php
@@ -8,19 +8,20 @@
namespace App\Collection;
use CallbackFilterIterator;
use Closure;
use InvalidArgumentException;
use Iterator;
use Traversable;
use function array_filter;
use function count;
use function iterator_count;
use function iterator_to_array;
/**
* Trait CollectionTrait
*
* @package App\Collection
* @author TLe, Tarmo Leppänen <tarmo.leppanen@protacon.com>
*
* @method __construct(Traversable $items)
*/
trait CollectionTrait
{
@@ -54,19 +55,21 @@ trait CollectionTrait
*/
public function get(string $className)
{
$filteredResources = $this->getFilteredItems($className);
/** @var Iterator $items */
$items = $this->getFilteredIterator($className)->getAll();
$items->rewind();
$current = $items->current();
if (count($filteredResources) !== 1) {
if ($current === null) {
$this->error($className);
}
return $filteredResources[0];
return $current;
}
/**
* @return Traversable
*
* @psalm-return Traversable<int, mixed>
*/
public function getAll(): Traversable
{
@@ -82,13 +85,7 @@ public function getAll(): Traversable
*/
public function has(?string $className = null): bool
{
$output = false;
if ($className !== null) {
$output = count(array_filter(iterator_to_array($this->items), $this->filter($className))) === 1;
}
return $output;
return $this->getFilteredIterator((string)$className)->count() === 1;
}
/**
@@ -104,15 +101,11 @@ public function count(): int
/**
* @param string $className
*
* @return array
* @return $this
*/
private function getFilteredItems(string $className): array
private function getFilteredIterator(string $className): self
{
return array_values(
array_filter(
iterator_to_array($this->items),
$this->filter($className)
)
);
/** @psalm-suppress UndefinedInterfaceMethod */
return new self(new CallbackFilterIterator($this->items->getIterator(), $this->filter($className)));
}
}

0 comments on commit d8d0247

Please sign in to comment.
You can’t perform that action at this time.