Overview
PHP code can be frustratingly opaque, especially when dealing with nested functions. Why not chain those functions instead?, (*1)
$filter = function ($item) { return $item === 'SOME'; };
// Offputting one-liner
echo implode('.', array_filter(explode('-', strtoupper(trim(' some-value'))), $filter))
// Multiple assignments
$value = ' some-value';
$value = trim($value);
$value = strtoupper($value);
$value = explode('-', $value);
$value = array_filter($value, $filter);
echo implode('.', $value);
// Easy to read pipe
echo take(' some-value')
->trim()
->strtoupper()
->explode('-', '$$')
->array_filter($filter)
->implode('.', '$$')
->get();
// prints 'SOME'
Installation
Via Composer:, (*2)
composer require aviator/pipe
Testing
Via Composer:, (*3)
composer test
Usage
Get a Pipe
object:, (*4)
$value = new Pipe('value');
$value = Pipe::take('value');
$value = take('value');
Then you can chain callables:, (*5)
$value->pipe('strtoupper');
And get the mutated value:, (*6)
echo $value->get();
// prints 'VALUE'
The pipe method is chainable:, (*7)
echo Pipe::take(' value')
->pipe('trim')
->pipe('strtoupper')
->get();
// prints 'VALUE'
Pipe uses a magic __call
to redirect other methods to the pipe
method, so you don't have to use pipe(...)
at all:, (*8)
echo Pipe::take(' value')
->trim()
->strtoupper()
->get();
// prints 'VALUE'
Arguments
You can use callables with arguments:, (*9)
echo Pipe::take('value')
->str_repeat(3)
->strtoupper()
->get();
// prints 'VALUEVALUEVALUE'
Pipe
will always pass the value you're mutating ('value' in the example above) as the first parameter., (*10)
This works most of the time, but since PHP has some unique parameter ordering, there are cases where it doesn't. In these cases you can use the placeholder, by default $$
, to represent the mutating value., (*11)
For example, implode()
:, (*12)
echo Pipe::take(['some', 'array'])
->implode('.', '$$')
->get();
// prints 'some.array'
Because implode()
takes the input value as its second parameter, we tell Pipe
where to put it using '$$'. Then when called the value is swapped in., (*13)
Closures
You may pipe any callable, including a closure:, (*14)
$closure = function ($item) { return $item . '-postfixed'; };
echo Pipe::take('value')
->pipe($closure)
->get();
// prints 'value-postfixed'
Other Stuff
License
This package operates under the MIT License (MIT). Please see LICENSE for more information., (*15)
Thanks
This is largely based on Sebastiaan Luca's idea and his Pipe\Item
class., (*16)