Recipes
Each recipe is a small domain from the library's own test suite (tests/Examples), where it runs on every commit.
A cart: one line per product
php
/** @extends ImmutableList<CartLine> */
final readonly class Cart extends ImmutableList
{
protected const TYPE = CartLine::class;
public function add(Product $product, int $quantity = 1): self
{
$index = $this->findIndex(fn(CartLine $line) => $line->product->sku->value === $product->sku->value);
if ($index === null) {
return $this->append(new CartLine($product, $quantity));
}
$line = $this->get($index);
return $this->replace($index, $line->withQuantity($line->quantity + $quantity));
}
public function totalCents(): int
{
return $this->reduce(fn(int $sum, CartLine $line) => $sum + $line->totalCents(), 0);
}
protected function assertInvariants(): void
{
if ($this->count() !== $this->uniqueBy(fn(CartLine $line) => $line->product->sku)->count()) {
throw new DomainException('A product appears in two cart lines.');
}
}
}add() keeps the rule by construction, and the invariant catches any other path, such as Cart::of($line, $sameProductLine).
A ledger: transactions that balance
php
/** @extends ImmutableList<Posting> */
final readonly class Transaction extends ImmutableList
{
protected const TYPE = Posting::class;
protected function assertInvariants(): void
{
if ($this->count() < 2) {
throw new DomainException('A transaction needs at least two postings.');
}
$totals = $this->foldBy(
fn(Posting $p) => $p->amount->currency,
0,
fn(int $sum, Posting $p) => $sum + $p->amount->cents,
);
if ($totals->any(fn(int $total) => $total !== 0)) {
throw new DomainException('Unbalanced transaction.');
}
}
}Balances per account across a journal are one chain:
php
$this->flatMap(fn(Transaction $t) => $t)
->filter(fn(Posting $p) => $p->amount->currency === $currency)
->foldBy(
fn(Posting $p) => $p->account,
Money::zero($currency),
fn(Money $balance, Posting $p) => $balance->add($p->amount),
); // ImmutableMap<Account, Money>Account implements Hashable, so two instances with the same code are the same key.
A schedule: no overlapping events
php
protected function assertInvariants(): void
{
$sorted = $this->sortBy(fn(Event $e) => $e->start);
$clash = $sorted->zip($sorted->drop(1))->findOrNull(fn(array $pair) => $pair[0]->overlaps($pair[1]));
if ($clash !== null) {
throw new DomainException(sprintf('"%s" overlaps "%s".', $clash[1]->title, $clash[0]->title));
}
}Sorted by start, an overlap always shows up between neighbours; zip() with drop(1) gives the neighbouring pairs. groupBy(fn(Event $e) => $e->day()) then splits the schedule into days, each still a Schedule.
An import: good rows and errors
php
$contacts = Contacts::builder();
$errors = ImportErrors::builder();
foreach ($lines as $number => $line) {
try {
$contacts->add(Contact::fromCsv($line));
} catch (InvalidArgumentException $e) {
$errors->add(new ImportError($number, $e->getMessage()));
}
}
return new ImportResult($contacts->build(), $errors->build());Two builders, one pass, O(n), and both results are typed collections.
Small ones
Index a list into a domain map:
php
$byEmail = UsersByEmail::fromIterable($users->keyBy(fn(User $u) => $u->email));Replace matching elements, keeping the domain type:
php
$updated = $categories->mapInto(Categories::class, fn(Category $c) => $c->slug === $slug ? $c->withTitle($title) : $c);Union of many sets:
php
$accounts = $transactions->flatMap(fn(Transaction $t) => $t->accounts())->toSet();