implementation d'une classe de collection

This commit is contained in:
Gregory Letellier
2023-10-31 10:42:12 +01:00
parent 47a64d4af0
commit 77c6ecfb2f
2 changed files with 138 additions and 0 deletions

86
src/Collection.php Normal file
View File

@@ -0,0 +1,86 @@
<?php
namespace Kletellier\PdoWrapper;
use ArrayIterator;
use IteratorAggregate;
use Traversable;
class Collection implements IteratorAggregate
{
private array $elements;
public function __construct(array $elements = [])
{
$this->elements = $elements;
}
public function first(): mixed
{
return reset($this->elements);
}
public function last(): mixed
{
return end($this->elements);
}
public function count(): int
{
return count($this->elements);
}
public function clear(): bool
{
$this->elements = [];
return count($this->elements) == 0;
}
public function reduce(callable $fn, mixed $initial): mixed
{
return array_reduce($this->elements, $fn, $initial);
}
public function map(callable $fn): Collection
{
$tmp = array_map($fn, $this->elements);
return new Collection($tmp);
}
public function each(callable $fn): void
{
array_walk($this->elements, $fn);
}
public function filter(callable $fn): Collection
{
$tmp = array_filter($this->elements, $fn, ARRAY_FILTER_USE_BOTH);
$collect = new Collection($tmp);
return $collect;
}
public function empty(): bool
{
return empty($this->elements);
}
public function add(mixed $element): void
{
$this->elements[] = $element;
}
public function values(): array
{
return array_values($this->elements);
}
public function items(): array
{
return $this->elements;
}
public function getIterator(): Traversable
{
return new ArrayIterator($this->elements);
}
}