camillebaronnet/collection

v0.4.0 2022-04-15 18:23 UTC

This package is auto-updated.

Last update: 2024-11-16 00:43:55 UTC


README

Collection provides a powerful data manipulation system based on the map/reduce/filter principles. Thanks to the php generators and the immutability, it allows to calculate the data as late as possible while preserving the memory.

Installation

composer require camillebaronnet/collection

How to use

public Collection::__construct(...$elements)
public Collection::__construct(\Traversable|array $elements)

Exemple :

$collection = (new Collection('foo', 'bar'))
    ->map(fn($word) => 'hello '.$word)
    ->map(fn($word) => strtoupper($word))
;

// The data is computed only here
var_dump($collection->toArray()); 
array(2) {
  [0]=>
  string(9) "HELLO FOO"
  [1]=>
  string(9) "HELLO BAR"
}

Basic operations

Note : As long as you use map/filter operations, nothing will be executed or stored in memory. If you decide to do more than one reduce or iterate operation, use get() first to before to buffer the previous operations.

Map

The map() function iterates over each element and applies the transformation function provided by the user.

map(fn($element) => /* ... */);

Example :

(new Collection(10, 50, 100))
    ->map(fn($element) => $element * 2)
    ->toArray()
;

// [20, 100, 200]

Filter

The filter() method test elements using that pass the test implemented by the provided function.

filter(fn ($element) => /* ... */);

Example :

(new Collection(10, 50, 100))
    ->filter(fn($element) => $element > 20)
    ->toArray()
;
// [50, 100]

Reduce

The reduce() method executes a reduction function provided by the user on each element, the result of each iteration is passed to the next iteration.

reduce(fn($carry, $currentValue, $currentKey) => /* ... */, $initial);

Example :

(new Collection(10, 50, 100))
    ->reduce(fn($carry, $current) => $carry + $current)
;
// 160

GroupBy

The method groupBy() returns a Collection of CollectionGroup. A CollectionGroup is a simple collection with a key property added.

groupBy(fn ($element) => /* ...  */);

Example :

$result = (new Collection([
        ['key1' => 'foo', 'key2' => 10],
        ['key1' => 'bar', 'key2' => 11],
        ['key1' => 'foo', 'key2' => 12],
        ['key1' => 'bar', 'key2' => 14],
    ]))
    ->groupBy(fn($x) => $x['key1'])
    ->toArray() // [CollectionGroup, CollectionGroup]
;

$result[0]->key; // 'foo'
$result[0]->toArray(); // [['key1' => 'foo', 'key2' => 10],['key1' => 'foo', 'key2' => 12],]