implementation d'une classe de collection
This commit is contained in:
86
src/Collection.php
Normal file
86
src/Collection.php
Normal 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user