lc5 / typed-collection
Create strictly typed collections in PHP
Installs: 18 607
Dependents: 0
Suggesters: 0
Security: 0
Stars: 4
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/lc5/typed-collection
Requires
- php: >=7.4.0
Requires (Dev)
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^9.5
- rector/rector: ^0.12.3
- symplify/easy-coding-standard: ^9.4
This package is not auto-updated.
Last update: 2025-10-25 12:30:10 UTC
README
Create strictly typed collections in PHP.
Installation
$ composer require lc5/typed-collection
AbstractTypedCollection:
An abstract class used to create strictly typed collections implemented as a type-checking wrapper around ArrayObject.
The type of elements in a collection is defined by extending AbstractTypedCollection and implementing abstract
AbstractTypedCollection::getType method. It should return the type as a string, which can be any class name or one
of the internal types in a form recognised by the internal gettype() function
("boolean", "integer", "double", "string", "array", "object", "resource", "NULL"). UnexpectedValueException
will be thrown, when trying to add an element with an invalid type.
Usage:
use Lc5\TypedCollection\AbstractTypedCollection; use Lc5\TypedCollection\Exception\UnexpectedValueException; class stdClassCollection extends AbstractTypedCollection { public function getType(): string { return \stdClass::class; //can be any class or internal type } } $collection = new stdClassCollection([new \stdClass(), new \stdClass()]); $collection[] = new \stdClass(); try { $collection[] = 'invalid'; } catch (UnexpectedValueException $e) { echo $e->getMessage(); //Invalid value type: string. Only \stdClass is allowed. } try { $collection = new stdClassCollection(['invalid', new \stdClass()]); } catch (UnexpectedValueException $e) { echo $e->getMessage(); //Invalid value type: string. Only \stdClass is allowed. }
TypedCollection:
A strictly typed collection based on ArrayObject. The type of elements in collection is defined using constructor
argument, which can be any class name or one of the internal types in a form recognised by internal
gettype() function ("boolean", "integer", "double", "string", "array", "object", "resource", "NULL"). UnexpectedValueException will be thrown, when trying to add element
with invalid type.
Usage:
use Lc5\TypedCollection\TypedArray; use Lc5\TypedCollection\Exception\UnexpectedValueException; $values = [new \stdClass(), new \stdClass()]; $typedCollection = new TypedCollection(\stdClass::class, $values); $typedCollection[] = new \stdClass(); try { $typedCollection[] = 'invalid'; } catch (UnexpectedValueException $e) { echo $e->getMessage(); //Invalid value type: string. Only \stdClass is allowed. }
The behavior is identical as in AbstractTypedCollection.