noi/array-walker

ArrayWalker, OOP wrapper for array_walk() and array_map()

dev-master 2013-09-19 10:13 UTC

This package is not auto-updated.

Last update: 2024-12-16 17:01:37 UTC


README

An OOP wrapper for the built-in array_walk() and array_map().

Installation

Using Composer, just $ composer require noi/array-walker package or:

{
    "require": {
        "noi/array-walker": "dev-master"
    }
}

Usage

Example 1:

<?php
$names = array('*APPLE*', '*ORANGE*', '*LEMON*');

$walker = new \Noi\Util\ArrayWalker($names);
$result = $walker->trim('*')->strtolower()->ucfirst();

assert($result->getArrayCopy() === array('Apple', 'Orange', 'Lemon'));
assert((array) $result === array('Apple', 'Orange', 'Lemon'));

The following code returns the same result as the above:

// ...
$result = $walker->map(function ($name) {
    return ucfirst(strtolower(trim($name, '*')));
});

Example 2:

<?php
$dom = new \DOMDocument();
$dom->loadXML('<users><user>Alice</user><user>Bob</user></users>');
$users = $dom->getElementsByTagName('user');

$walker = new \Noi\Util\ArrayWalker($users);
$walker->setAttribute('type', 'engineer');

assert(trim($dom->saveHtml()) ==
    '<users><user type="engineer">Alice</user><user type="engineer">Bob</user></users>');

The following code returns the same result as the above:

// ...
$walker->walk(function ($node) {
    $node->setAttribute('type', 'engineer');
});

License

ArrayWalker is licensed under the MIT License - see the LICENSE file for details.