Write your own reducerΒΆ
Typically, a reducer function has the following signature:
1<?php
2
3function reducer(mixed $accumulator, mixed $item): mixed {
4 // Update the accumulator based on the item and return it.
5}
PHP out of the box provides several built-in functions that can be used as reducers, such as array_sum, array_product, and count. These functions can be used to perform common reduction operations on arrays.
There is also a general-purpose array reducer function called array_reduce that allows you to define custom reduction logic.
These library deviates from the traditional implementation of reducers in order to accommodate possibility of reducing streams to a single value without the breaking the stream from emitting items.
For that purpose, reducers are stateful objects that maintain an internal state throughout the reduction process. They expose methods to process each item and retrieve the reduced value.
Reducers in this library implement the
RunOpenCode\Component\Dataset\Contract\ReducerInterface interface, which
defines the following members:
1<?php
2
3declare(strict_types=1);
4
5namespace RunOpenCode\Component\Dataset\Contract;
6
7/**
8 * Interface for dataset reducers.
9 *
10 * Each reducer is a simple, stateful class instance which does
11 * data reduction. For each iteration, aggregates the value and
12 * stores it into value property.
13 *
14 * @template TKey
15 * @template TValue
16 * @template TReducedValue
17 */
18interface ReducerInterface
19{
20 /**
21 * Reduced value.
22 *
23 * @var TReducedValue
24 */
25 public mixed $value {
26 get;
27 }
28
29 /**
30 * Provide key and value from next iteration for reduction.
31 *
32 * @param TValue $value Value from current iteration.
33 * @param TKey $key Key from current iteration.
34 */
35 public function next(mixed $value, mixed $key): void;
36}
Note
Remember, reducers are stateful. Each instance maintains its own state during the reduction process and reduced value can be retrieved before, during, or after the stream iteration.