Piper enhances the PHP 8.5 pipe operator (|>) with support for multi-argument functions/callables.
Background
In PHP the pipe operator (|>) works with single-argument callables, such as strlen, trim, etc..,
$nonce = random_bytes(16)
|> base64_encode(...); but what if you want to use it with multi-argument callables, such as rtrim, strtr, etc..
// does not work
$nonce = random_bytes(16)
|> base64_encode(...)
|> strtr(..., '+/', '-_')
|> rtrim(..., '='); // works but too verbose
$nonce = random_bytes(16)
|> base64_encode(...)
|> (fn(string $s): string => strtr($s, '+/', '-_'))
|> (fn($s) => rtrim($s, '=')); This is where Piper comes into play!
Piper is sort of a decorator/wrapper around a callable for the pipe operator |>.
composer require burnett01/php-piper
PSR-4 function version:
use function Burnett01\Piper\with;
$nonce = random_bytes(16)
|> base64_encode(...)
|> with('strtr', '+/', '-_')
// first-class syntax
|> with(rtrim(...), '=');
// or pipe() function
use function Burnett01\Piper\pipe;
$nonce = random_bytes(16)
|> base64_encode(...)
|> pipe('strtr', '+/', '-_')
// with first-class syntax
|> pipe(rtrim(...), '=');PSR-4 class version:
use Burnett01\Piper\Piper as pipe;
$nonce = random_bytes(16)
|> base64_encode(...)
|> pipe::to('strtr', '+/', '-_')
// or 'with' + first-class syntax
|> pipe::with(rtrim(...), '='); The ellipsis ... represents the first-class callable syntax.
You can use a callable as string or first-class syntax for passing the method.
use function Burnett01\Piper\with;
$actual = -1234.5
|> abs(...)
|> with(number_format(...), 2, '.', ',')
|> urlencode(...);-
Creates an instance of Piper for the specificed
$fn.Parameters:
-
callable
$fn- The name of a callable as string (eg.'strlen') or as first-class syntax (eg.strlen(...)) -
variadic (mixed)
$args- The arguments for$fn
Context: static
Returns: instance
-
-
alias for
Piper::to(callable $fn, mixed ...$args)(see above) -
alias for
Piper::to(callable $fn, mixed ...$args)(see above) -
alias for
Piper::to(callable $fn, mixed ...$args)(see above)
