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);
}
}

52
tests/CollectionTest.php Normal file
View File

@@ -0,0 +1,52 @@
<?php
use Kletellier\PdoWrapper\Collection;
test("collection", function () {
$arr = [];
for ($i=0; $i < 11; $i++) {
$arr[] = $i;
}
expect(count($arr))->toBe(11);
$coll = new Collection($arr);
expect($coll->count())->toBe(11);
expect($coll->first())->toBe(0);
expect($coll->last())->toBe(10);
$filt = $coll->filter(function($item){ return $item<5;});
expect($filt)->toBeInstanceOf(Collection::class);
expect($filt->count())->toBe(5);
expect($filt->first())->toBe(0);
expect($filt->last())->toBe(4);
// no change in initial collection
expect($coll->count())->toBe(11);
expect($coll->empty())->toBe(false);
expect($coll->items())->toBeArray();
expect(count($coll->items()))->toBe(11);
$incr = 0;
$coll->each(function($item) use(&$incr){
$incr++;
});
expect($incr)->toBe(11);
$colmap = $coll->map(function($item) {
return $item+1;
});
expect($colmap)->toBeInstanceOf(Collection::class);
expect($colmap->count())->toBe(11);
expect($colmap->first())->toBe(1);
expect($colmap->last())->toBe(11);
$init = 0;
$reduce = $coll->reduce(function($item,$carry){
return $item + $carry;
},$init);
expect($reduce)->toBe(55);
});