oliverdavies.uk/src/Presentation/Collection/Collection.php

56 lines
963 B
PHP
Raw Normal View History

2025-05-04 21:32:34 +01:00
<?php
declare(strict_types=1);
namespace App\Presentation\Collection;
use ArrayIterator;
use Countable;
use Iterator;
use IteratorAggregate;
2025-05-04 21:45:20 +01:00
/**
2025-05-04 22:37:31 +01:00
* @implements IteratorAggregate<TItem>
2025-05-04 21:45:20 +01:00
* @template TItem
*/
class Collection implements Countable, IteratorAggregate
2025-05-04 21:32:34 +01:00
{
2025-05-04 21:45:20 +01:00
/**
* @param TItem[] $items
*/
final public function __construct(protected array $items = [])
2025-05-04 21:32:34 +01:00
{
}
public function count(): int
{
return count($this->items);
}
2025-05-04 22:37:31 +01:00
/**
* @return self<TItem>
*/
2025-05-04 21:32:34 +01:00
public function filter(callable $callback): self
{
return new static(
array_filter(
array: $this->items,
callback: $callback,
)
);
}
public function getIterator(): Iterator
{
return new ArrayIterator($this->items);
}
2025-05-04 21:45:20 +01:00
/**
* @return TItem[]
*/
2025-05-04 21:32:34 +01:00
public function toArray(): array
{
return $this->items;
}
}