aeviiq / collection
A library that provides strict typed collections in PHP.
Installs: 25 821
Dependents: 4
Suggesters: 0
Security: 0
Stars: 6
Watchers: 4
Forks: 5
Open Issues: 0
Requires
- php: ^8.1
Requires (Dev)
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2024-11-20 14:02:49 UTC
README
Why
To provide an easy way to ensure type safety on collections/arrays and provide useful custom methods for object collections, as seen in the example below.
Installation
composer require aeviiq/collection
Declaration
/** * @extends ObjectCollection<int, Foo> * * @method \ArrayIterator|Foo[] getIterator() * @method Foo|null first() * @method Foo|null last() */ final class FooCollection extends ObjectCollection { public function filterReleasedBefore(\DateTimeInterface $dateTime): FooCollection { return $this->filter(static function (Foo $foo) use ($dateTime): bool { return $foo->getReleaseDate() < $dateTime; }); } public function filterActives(): FooCollection { return $this->filter(static function (Foo $foo): bool { return $foo->isActive(); }); } protected function allowedInstance(): string { return Foo::class; } }
Usage
// Useful custom methods for ObjectCollections: $fooCollection = new FooCollection([$foo1, $foo2]); $result = $fooCollection->filterReleasedBefore(new DateTime('now'))->filterActives(); // Basic type collections that are provided $intCollection = new IntCollection([1, 2]); $intCollection->append(3); $intCollection = new IntCollection([1, '2']); // InvalidArgumentException thrown $intCollection->append('3'); // InvalidArgumentException thrown