Search by

eugeneerg / collections

EugeneErg

Immutable typed collections for PHP: runtime-checked and PHPStan-typed

Package info

github.com/EugeneErg/Collections

pkg:composer/eugeneerg/collections

Statistics

Installs: 44

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

1.4.0 2026-12-02 16:39 UTC

README

English | Русский

Immutable typed collections for PHP 8.2+. The element type is checked twice:

  • at runtime: Users::of($order) throws InvalidElementType;
  • statically: PHPStan knows that Users holds User objects, and it checks the declared type against @extends on its own.

The main use case is domain collections such as Users, OrderLines or Tags, each with its own type and invariants.

Documentation: https://eugeneerg.github.io/collections-docs/ — guides, recipes and this reference.

Installation

composer require eugeneerg/collections

It requires PHP 8.2+. If your project uses PHPStan, you need version 2.3.7 or newer. Older versions report false errors for the TYPE check, so Composer refuses to install the package next to them.

A domain list

use EugeneErg\Collections\ImmutableList;

/** @extends ImmutableList<User> */
final readonly class Users extends ImmutableList
{
    protected const TYPE = User::class;
}

$users = Users::of($alice, $bob);
$users = Users::fromIterable($repository->findAll());

Users::of($order);
// InvalidElementType: Users[0] expects User, got Order.
// PHPStan: Parameter #1 ...$items of static method ImmutableList<User>::of() expects User, Order given.

TYPE is a class, interface or enum name, or one of 'int', 'float', 'string', 'bool' and 'null'. For a union, use a non-empty list:

protected const TYPE = [Cat::class, Dog::class];   // @extends ImmutableList<Cat|Dog>
protected const TYPE = [User::class, 'null'];      // @extends ImmutableList<User|null>
protected const TYPE = ['int', 'string'];          // @extends ImmutableList<int|string>

With the library's PHPStan extension (see Static analysis), PHPStan checks that TYPE matches @extends: TYPE = Order::class with @extends ImmutableList<User> is a classConstant.phpDocType error, and a class without @extends is a missingType.generics error. A subclass that forgets TYPE throws InvalidTypeDeclaration the first time it is created.

For types that TYPE cannot express, override elementType():

/** @extends ImmutableList<positive-int> */
final readonly class Quantities extends ImmutableList
{
    protected static function elementType(): Type
    {
        return new CallbackType(static fn(mixed $v): bool => is_int($v) && $v > 0, 'positive-int');
    }
}

Invariants

assertInvariants() runs for every new instance, including the results of filter(), slice() and remove(), so no operation can produce a broken collection:

protected function assertInvariants(): void
{
    if ($this->isEmpty()) {
        throw new EmptyOrder();
    }
}

Invariants may use the collection's own operations; see Domain collections.

Immutability

The classes are readonly, and so are their subclasses. Every operation returns a new instance; there is no ArrayAccess. Operations check only what they add, and invariants run for every new instance. To build a collection in a loop, use X::builder(): it is O(n) where append() in a loop is O(n²). See Lists, sets and maps.

JSON, serialization and frameworks

Collections implement JsonSerializable; serialize()/unserialize() work and check the data. To build collections from JSON, use Valinor (works out of the box), eugeneerg/collections-symfony for Symfony Serializer, or Hydrator with any mapper; CollectionShape describes a collection class for your own bridge. See JSON and frameworks.

ImmutableList

Create of(...), fromIterable(), empty(), builder(), new X(iterable)
Read get, getOrNull, first, firstOrNull, last, lastOrNull, contains, indexOf, findIndex, find, findOrNull, any, all, none, reduce, equals, count, isEmpty, toArray
Same class filter, reject, sort, sortBy, sortWith, reverse, slice, take, drop, unique, uniqueBy, append, appendAll, prepend, insert, replace, remove, concat, shuffle, chunk → list<static>, partition → [static, static]
Other type map → ImmutableList<U>, mapInto(Users::class, fn) → Users, flatMap, groupBy → ImmutableMap<K, static>, keyBy → ImmutableMap<K, T>, countBy → ImmutableMap<K, int>, foldBy → ImmutableMap<K, R>, toSet → ImmutableSet<T>, zip

sort(), sortBy() keys, and sortByKey()/sortByValue() without a comparator use natural order (<=>). It is allowed only for scalars, null, dates and arrays of them; for enums and other objects <=> gives no meaningful order, so these methods throw NotComparable. Sort by a scalar key instead: sortBy(fn(Status $s) => $s->value).

Ready-made scalar lists: IntList and FloatList (sum, average, min, max), and StringList (join).

ImmutableSet

Unique elements in order of first appearance. Adding an element that is already there changes nothing.

/** @extends ImmutableSet<Tag> */
final readonly class Tags extends ImmutableSet
{
    protected const TYPE = Tag::class;
}

$tags = Tags::of(new Tag('php'), new Tag('ddd'), new Tag('php')); // 2 tags
$tags->contains(new Tag('php'));                                  // true, O(1)
$tags->union($other)->intersect($filter)->diff($banned);          // O(1) per element

Equality is the same as everywhere in the library: strict, and by identity() for objects that implement Hashable. Elements must be hashable: int, string, float, bool, null or objects, not arrays.

Methods: of, fromIterable, empty, builder, contains, containsAll, containsAny, isSubsetOf, equals, with, without, union, intersect, diff, filter, reject, map → ImmutableSet<U>, mapInto, find, findOrNull, any, all, reduce, toList, toArray, count, isEmpty.

ImmutableMap

Keys keep their exact type: "1", 1, 1.0 and true are four different keys, and an object can be a key.

/** @extends ImmutableMap<UserId, User> */
final readonly class UsersById extends ImmutableMap
{
    protected const KEY_TYPE = UserId::class;
    protected const VALUE_TYPE = User::class;
}

$users = UsersById::fromPairs([[new UserId(1), $alice]]);
$users->get(new UserId(1)); // $alice, because UserId implements Hashable

Objects are compared by instance, and objects that implement Hashable are compared by identity(). The same rule applies in sets and in contains(), indexOf(), unique(), uniqueBy() and equals().

Methods: fromIterable, fromPairs, empty, builder, get, getOrNull, has, keys, values, pairs, with, withMerged, withAll, without, merge, filter, reject, map, mapInto, mapKeys, sortByKey, sortByValue, reduce, any, all, equals, toArray.

toArray() and json_encode() throw UnsupportedKey when a key is not int|string, or when two keys merge into one array key (1 and "1").

Exceptions

All of them implement EugeneErg\Collections\Exception\CollectionException:

  • InvalidElementType: an element or key has the wrong type;
  • InvalidTypeDeclaration: TYPE is wrong (a programming error);
  • ElementNotFound: no such index or key, the collection is empty, or find() found no match;
  • UnsupportedKey: the key cannot be used, or cannot be converted to an array key;
  • InvalidSerializedData: unserialize() got data that is not a serialized collection;
  • NotComparable: natural order was requested for values that have none;
  • UncheckedInstanceEscaped: assertInvariants() kept a temporary of its own class;
  • NotACollection: CollectionShape::of() got a class that is not a collection;
  • HydrationFailed: Hydrator got data that is not iterable.

Static analysis

Generics work in PHPStan and Psalm. The PHPStan extension also checks TYPE, KEY_TYPE and VALUE_TYPE against @extends; include it by hand:

includes:
    - vendor/eugeneerg/collections/extension.neon

See Static analysis.

Versioning

The package follows Semantic Versioning; changes are listed in CHANGELOG.md.

The public API, which does not break within a major version, is everything in the EugeneErg\Collections namespace except:

  • the EugeneErg\Collections\Internal namespace;
  • elements marked @internal, such as the builder constructors (get builders from X::builder()).

The extension points are part of the public API: the TYPE, KEY_TYPE and VALUE_TYPE constants, and the protected elementType(), keyType(), valueType() and assertInvariants() methods.

Not covered: the wording of exception messages, and more precise PHPStan/Psalm types, which a minor version may add. The minimum PHP version is raised only in a major version.

Development

composer check   # php-cs-fixer, phpstan (level max + strict rules + bleeding edge), phpunit

CI runs the tests on PHP 8.2–8.5, including a run with the lowest dependencies, and measures coverage. Mutation testing with Infection must reach 100% MSI.

The tests/PHPStan test runs PHPStan on fixtures and compares its errors with the // error: <identifier> markers in them. This protects the TYPE ↔ @extends check and generics inference from regressions when PHPStan is upgraded.

The design and the decision log are in docs/concept.md and docs/decisions.md (in Russian).