The Collection
library provides a flexible and efficient API to manipulate, iterate, and manage collections in a
structured and type-safe manner.
It leverages PHP's Generators for optimized memory usage and lazy evaluation, ensuring that large datasets are handled efficiently without loading all elements into memory at once.
The library supports adding, removing, filtering, sorting, and transforming elements.
composer require tiny-blocks/collection
The library exposes the available behaviors through the Collectible
interface and provides utilities to manipulate
collections of various types.
The Collection
class implements the Collectible
interface and provides a concrete implementation for handling
collections.
It allows for adding, removing, filtering, and sorting elements, as well as transforming them into different formats like arrays and JSON.
The class is designed to work with generic key-value pairs, ensuring type safety and flexibility for a variety of use cases.
<?php
declare(strict_types=1);
namespace Example;
use TinyBlocks\Collection\Collection;
use TinyBlocks\Collection\Internal\Operations\Order\Order;
use TinyBlocks\Collection\Internal\Operations\Transform\PreserveKeys;
$collection = Collection::createFrom(elements: [1, 2, 3, 4, 5])
->add(elements: [6, 7])
->filter(predicates: fn(int $value): bool => $value > 3)
->sort(order: Order::ASCENDING_VALUE)
->map(transformations: fn(int $value): int => $value * 2)
->toArray(preserveKeys: PreserveKeys::DISCARD);
# Output: [8, 10, 12, 14]
These methods enable adding, removing, and modifying elements in the Collection.
-
add
: Adds one or more elements to the Collection.$collection->add(elements: [1, 2, 3]);
$collection ->add('X', 'Y', 'Z');
-
remove
: Removes a specific element from the Collection.$collection->remove(element: 1);
-
removeAll
: Removes elements from the Collection.-
With a filter: Removes only the elements that match the provided filter.
$collection->removeAll(filter: fn(Amount $amount): bool => $amount->value > 10.0);
-
Without a filter: Removes all elements from the Collection.
$collection->removeAll();
-
These methods enable filtering elements in the Collection based on specific conditions.
-
filter
: Filters elements in the Collection.-
With predicates: Filter elements are based on the provided predicates.
$collection->filter(predicates: fn(Amount $amount): bool => $amount->value > 100);
-
Without predicates: Removes all empty or false values (e.g.,
null
,false
, empty arrays).$collection->filter();
-
These methods enable sorting elements in the Collection based on the specified order and optional predicates.
-
sort
: Sorts the Collection.Order::ASCENDING_KEY: Sorts the collection in ascending order by key. Order::DESCENDING_KEY: Sorts the collection in descending order by key. Order::ASCENDING_VALUE: Sorts the collection in ascending order by value. Order::DESCENDING_VALUE: Sorts the collection in descending order by value.
By default,
Order::ASCENDING_KEY
is used.use TinyBlocks\Collection\Internal\Operations\Order\Order; $collection->sort(order: Order::DESCENDING_VALUE);
Sort the Collection using a custom predicate to determine how elements should be compared.
use TinyBlocks\Collection\Internal\Operations\Order\Order; $collection->sort(order: Order::ASCENDING_VALUE, predicate: fn(Amount $amount): float => $amount->value);
These methods allow access to elements within the Collection, such as fetching the first or last element, counting the elements, or finding elements that match a specific condition.
-
count
: Returns the total number of elements in the Collection.$collection->count();
-
findBy
: Finds the first element that matches one or more predicates.$collection->findBy(predicates: fn(CryptoCurrency $crypto): bool => $crypto->symbol === 'ETH');
-
first
: Retrieves the first element from the Collection or returns a default value if the Collection is empty.$collection->first(defaultValueIfNotFound: 'default');
-
getBy
: Retrieves an element by its index or returns a default value if the index is out of range.$collection->getBy(index: 0, defaultValueIfNotFound: 'default');
-
last
: Retrieves the last element from the Collection or returns a default value if the Collection is empty.$collection->last(defaultValueIfNotFound: 'default');
-
slice
: Extracts a portion of the collection, starting at the specified index and retrieving the specified number of elements. If length is negative, it excludes many elements from the end of the collection. If length is not provided or set to -1, it returns all elements from the specified index to the end of the collection.$collection->slice(index: 1, length: 2);
These methods enable comparing collections to check for equality or to apply other comparison logic.
-
contains
: Checks if the Collection contains a specific element.$collection->contains(element: 5);
-
equals
: Compares the current Collection with another collection to check if they are equal.$collectionA->equals(other: $collectionB);
These methods perform operations that return a single value based on the Collection's content, such as summing or combining elements.
-
reduce
: Combines all elements in the Collection into a single value using the provided aggregator function and an initial value. This method is helpful for accumulating results, like summing or concatenating values.$collection->reduce(aggregator: fn(float $carry, float $amount): float => $carry + $amount, initial: 0.0)
These methods allow the Collection's elements to be transformed or converted into different formats.
-
each
: Executes actions on each element in the Collection without modification. The method is helpful for performing side effects, such as logging or adding elements to another collection.$collection->each(actions: fn(Invoice $invoice): void => $collectionB->add(elements: new InvoiceSummary(amount: $invoice->amount, customer: $invoice->customer)));
-
groupBy
: Groups the elements in the Collection based on the provided grouping criterion.$collection->groupBy(grouping: fn(Amount $amount): string => $amount->currency->name);
-
map
: Applies transformations to each element in the Collection and returns a new collection with the transformed elements.$collection->map(transformations: fn(int $value): int => $value * 2);
-
toArray
: Converts the Collection into an array.PreserveKeys::DISCARD: Converts while discarding the keys. PreserveKeys::PRESERVE: Converts while preserving the original keys.
By default,
PreserveKeys::PRESERVE
is used.use TinyBlocks\Collection\Internal\Operations\Transform\PreserveKeys; $collection->toArray(preserveKeys: PreserveKeys::DISCARD);
-
toJson
: Converts the Collection into a JSON string.PreserveKeys::DISCARD: Converts while discarding the keys. PreserveKeys::PRESERVE: Converts while preserving the original keys.
By default,
PreserveKeys::PRESERVE
is used.use TinyBlocks\Collection\Internal\Operations\Transform\PreserveKeys; $collection->toJson(preserveKeys: PreserveKeys::DISCARD);
The Collection
class leverages PHP's Generators to
provide lazy evaluation, meaning elements are only generated as needed.
It cannot be reused once a generator is consumed (i.e., after you iterate over it or apply certain operations).
This behavior is intended to optimize memory usage and performance but can sometimes lead to confusion when reusing an
iterator after operations like count
, toJson
, or toArray
.
Lazy evaluation, enabled by PHP's Generators, allows
Collection
to handle large datasets without loading all elements into memory at once.
This results in significant memory savings when working with large datasets or performing complex chained operations.
However, this also means that some operations will entirely consume the generator, and you won't be
able to reaccess the elements unless you recreate the Collection
.
Collection is licensed under MIT.
Please follow the contributing guidelines to contribute to the project.