renanbr/iterant

Dynamically mutable iterator

dev-master 2016-02-05 09:39 UTC

This package is auto-updated.

Last update: 2020-10-05 10:46:17 UTC


README

Build Status

Iterant is a PHP library that implements the Iterator interface.

Features:

  • To append and prepend elements in runtime;
  • To run a callable for each element.
class RenanBr\Iterant implements Iterator
{
    public function __construct(callable $mapper = null);

    /* Inserts the specified value as the last item of the list.
     * If $target is given, inserts after it. */
    public function append(mixed $value, mixed $target = null): void;

    /* Inserts the specified value as the first item of the list.
     * If $target is given, inserts before it. */
    public function prepend(mixed $value, mixed $target = null): void;

    /* and, evidently, all Iterator methods */
    public function current(): mixed;
    public function key(): int;
    public function next(): void;
    public function rewind(): void;
    public function valid(): bool;
}

Install

composer require renanbr/iterant

Usage

Adding items dynamically

$iterator = new RenanBr\Iterant;
$iterator->append('first');
$iterator->append('second');
$iterator->append('third');
$iterator->prepend('before the first');

foreach ($iterator as $item) {
    if ($item == 'first') {
        $iterator->append('second and half', 'second');
    }
    if ($item == 'third') {
        // insert non catchable items
        $iterator->append('hidden', 'second');
        $iterator->prepend('mystery', 'third');

        $iterator->append('fourth', 'third');
    }
    echo $item . "\n";
}

/* Result:
 *     before the first
 *     first
 *     second
 *     second and half
 *     third
 *     fourth
 */

Mapping

You can optionally apply a callback for each element. The sample bellow shows how to get items from a container.

$container = new RenanBr\Sack;
$container->set('first', 'Bob');
$container->set('second', 'John');

$iterator = new RenanBr\Iterant([$container, 'get']);
$iterator->append('first');
$iterator->append('second');

foreach ($iterator as $item) {
    echo "Hello $item!\n";
}

/*
 * Result:
 *     Hello Bob!
 *     Hello John!
 */

This sample uses renanbr/sack as ContainerInterface implementation.