Search by

blueprintau / collections

mineubob

A pure, standalone array wrapper for BlueprintAU — generic Collection and Enumerable contract with no dependencies.

Package info

github.com/blueprintau/collections

pkg:composer/blueprintau/collections

Statistics

Installs: 121

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

1.1.1 2026-10-05 17:23 UTC

This package is auto-updated.

Last update: 2026-11-12 22:09:13 UTC


README

PHP Tests Coverage Packagist

A pure, standalone array wrapper for the BlueprintAU ecosystem. This is the generic collection package — no model imports, no framework coupling. It is the one package every other BlueprintAU package can depend on without circularity.

Dependencies

None. This is a pure, standalone array wrapper.

Installation

composer require blueprintau/collections

Usage

use BlueprintAU\Collections\Collection;

// Constructors are protected — create instances via the static factories.
$users = Collection::make([
    ['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
    ['id' => 2, 'name' => 'Bob',   'role' => 'user'],
    ['id' => 3, 'name' => 'Carol', 'role' => 'user'],
]);

// Transforms (immutable — each returns a new Collection)
$names  = $users->pluck('name');                   // ['Alice', 'Bob', 'Carol']
$byId   = $users->keyBy('id');                     // [1 => [...], 2 => [...], 3 => [...]]
$byRole = $users->groupBy('role');                 // ['admin' => [...], 'user' => [...]]
$admins = $users->filter(fn ($u) => $u['role'] === 'admin');  // [Alice]
$upper  = $users->map(fn ($u) => strtoupper($u['name']));     // ['ALICE', 'BOB', 'CAROL']

// Predicate & streaming transforms
$young  = $users->filterMap(fn ($u) => $u['age'] < 18 ? $u['name'] : null);  // nulls dropped, keys preserved
$notAdmin = $users->reject(fn ($u) => $u['role'] === 'admin');
$prefix = Collection::make([1, 2, 3, 9])->takeWhile(fn ($v) => $v < 3);  // [1, 2]
$from3  = Collection::make([1, 2, 3, 9])->skipUntil(fn ($v) => $v === 3); // [3, 9]

// Reductions
$count    = $users->count();                       // 3
$total    = Collection::make([1, 2, 3,  ̀4])->sum(); // 10
$avg      = Collection::make([1, 2, 3, 4])->avg(); // 2.5
$hasAdmin = $users->contains(fn ($u) => $u['role'] === 'admin');  // true
$empty    = $users->isNotEmpty();                  // true
$only     = $users->sole('id', 1);                 // Alice's row (throws on 0 or 2+ matches)
$csv      = $users->implode(', ', 'name');         // 'Alice, Bob, Carol'

// Selection
$firstTwo = $users->take(2);                       // [Alice, Bob]
$sorted   = Collection::make([
    ['name' => 'Carol'],
    ['name' => 'Alice'],
    ['name' => 'Bob'],
])->sortBy('name');                               // [Alice, Bob, Carol]
$unique   = Collection::make([1, 1, 2,  ̀3,  ̀3])->unique();  // [1, 2, 3]

// Iteration
$users->each(fn ($u) => print($u['name'] . "\n")); // Alice Bob Carol
$first = $users->first();                          // Alice's row
$firstUser = $users->firstWhere('role', 'user');   // Bob's row

// Conversion
$array = $users->toArray();                        // plain array
$json  = $users->toJson();                         // JSON string

The Enumerable contract

Enumerable is the contract both Collection and LazyCollection implement. It extends \IteratorAggregate and \JsonSerializable, so any collection is foreach-able and json_encode()-able.

Only methods that behave identically whether the data is eagerly in memory or lazily streamed belong on the contract. Anything that forces materialization (count, sort, unique, toArray) stays on Collection.

The LazyCollection

LazyCollection is the lazy counterpart to Collection. Instead of holding items in memory, it streams them through a generator source on demand.

  • Transforms are lazy — map, filter, pluck, take, skip, slice, and friends return a new LazyCollection that pulls from the previous one only when iterated. This makes it possible to work with infinite or very large sources without materializing them.
  • Terminal operations materialize — toArray, count, toJson, all, sort, sortBy, unique, and reverse consume the stream.
  • Re-iterable — the source is stored as a factory closure, so each iteration produces a fresh generator. Pass a callable source (e.g. a generator function) to replay the stream. Non-callable sources are wrapped via yield from, which rewinds re-iterable iterators (e.g. ArrayIterator) automatically. A raw Generator is single-use: iterating it twice throws a "Cannot rewind a generator that was already run" exception rather than silently returning wrong data.
use BlueprintAU\Collections\LazyCollection;

// An infinite sequence, safely truncated.
$lazy = LazyCollection::make(function (): \Generator {
    $i = 1;
    while (true) {
        yield $i++;
    }
});

$firstFive = $lazy->take(5)->all(); // [1, 2, 3, 4, 5]

Memory and concurrency contracts

  • Memory model — transforms are O(1) memory: each item is pulled, processed, and released. Operations that inherently need the whole stream accumulate internally: count, sort, sortBy, reverse, toArray, toJson, all, groupBy, and unique (which keeps a "seen" set that grows with the number of distinct values). take/skip/slice with negative arguments must reach the end of the stream and materialize internally. On an infinite source, any accumulating operation will run forever or exhaust memory — there is no guard; prefer take() to bound infinite streams before applying terminal operations.
  • Concurrency model — a LazyCollection is not safe for concurrent iteration. Each getIterator() call produces a fresh generator from the source factory, but two consumers iterating the same underlying single-use source (e.g. a shared raw Generator, a socket, a cursor) will silently split its items between them — each item goes to exactly one consumer, with no error. This applies through transforms too: a mapped or filtered view shares the parent's source. Iterate a LazyCollection from one consumer at a time, or wrap a shared source in a caching layer before handing it to multiple consumers.
  • Immutability — Collection is immutable: writes through ArrayAccess ($collection[$k] = $v, unset($collection[$k])) throw a BadMethodCallException. Transforms return new instances. Note that immutability is shallow: the collection never mutates its own structure, but mutable elements (objects, arrays) are shared by reference between the original and derived collections — mutating an element mutates it everywhere. Subclasses that add mutable state must preserve the transform-immutability contract themselves.

Requirements

PHP 8.4 or newer.

Testing

composer install
composer test          # PHPUnit
composer analyse       # PHPStan (level 8)
composer security:audit  # dependency security advisories

CI runs the test suite across PHP 8.4 / 8.5 (lowest and highest dependencies) on every push and pull request. Releases are cut from the Release workflow (Actions → Release), which takes a version tag, verifies it does not already exist, runs the full test suite, then creates the tag and GitHub Release.

License

MIT