marvin255 / fluent-iterable
Fluent interface for PHP iterable.
v0.12.5
2024-06-08 13:02 UTC
Requires
- php: >=8.1
- marvin255/data-getter-helper: ^0.5
- marvin255/optional: ^0.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- infection/infection: ^0.27
- phpunit/phpunit: ^10.0
- vimeo/psalm: ^5.0
README
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)