marvin255/fluent-iterable

Fluent interface for PHP iterable.

v0.12.5 2024-06-08 13:02 UTC

This package is auto-updated.

Last update: 2024-10-31 07:48:39 UTC


README

Latest Stable Version Total Downloads License Build Status

Object that provides map, filter and other array related functions for any iterable instances (array, Iterator, Generator) in a simple fluent style.

use Marvin255\FluentIterable\FluentIterable;
use Marvin255\FluentIterable\Helper\Reducer;
use Marvin255\FluentIterable\Helper\Filter;
use Marvin255\FluentIterable\Helper\Compare;

$input = [1, 2, 3, 4];
$result = FluentIterable::of($input)
    ->skip(1)
    ->filter(Filter::compare(Compare::LESS_THEN, 4))
    ->map(fn (int $item): int => $item + 1)
    ->reduce(Reducer::sum())
    ->get();

Installation

Install via composer:

composer req marvin255/fluent-iterable

Usage

Initiate item using factory (any iterable instances are allowed)

$fluent = FluentIterable::of($input);

Apply intermediate methods (merge, filter, map, skip, limit, sorted, peek, distinct, flatten)

$fluent = $fluent->map(fn (int $item): int => $item + 1)
    ->filter(Filter::compare(Compare::LESS_THEN, 4))
    ->skip(1);

Get result using one of finalizing methods (walk, reduce, findByIndex, findOne, findFirst, findLast, toArray, getIterator, count, matchAll, matchNone, matchAny)

$result = $fluent->toArray();

Methods that convert list to a single item (reduce, findOne, findByIndex, findFirst, findLast) return an Optional instance.

Debugging

peek method might be used to show intermediate data.

use Marvin255\FluentIterable\FluentIterable;
use Marvin255\FluentIterable\Helper\Reducer;
use Marvin255\FluentIterable\Helper\Filter;
use Marvin255\FluentIterable\Helper\Compare;

$input = [1, 2, 3, 4];
$result = FluentIterable::of($input)
    ->filter(Filter::compare(Compare::LESS_THEN, 3))
    ->peek(
        function (mixed $item): void {
            var_dump($item);
        }
    )
    ->reduce(Reducer::sum())
    ->get();

It will output something like

int(1)
int(2)