Skip to content

Instantly share code, notes, and snippets.

@Phil-Venter
Created March 8, 2024 14:03
Show Gist options
  • Save Phil-Venter/9be22cb653ac456cc46d442d52e82d7c to your computer and use it in GitHub Desktop.
Save Phil-Venter/9be22cb653ac456cc46d442d52e82d7c to your computer and use it in GitHub Desktop.
Simple PHP pipe implementation
class Compose
{
    public static function pipe(callable ...$fns): Closure
    {
        return function ($initial) use ($fns) {
            return array_reduce($fns, fn ($prev, $curr) => $curr($prev), $initial);
        };
    }
}

Usage:

function encodeString(
    string $string
): string {
    return Compose::pipe(
        fn ($x) => trim($x),
        fn ($x) => gzdeflate($x),
        fn ($x) => bin2hex($x),
    )($string);
}

function decodeString(
    string $string
): string {
    return Compose::pipe(
        fn ($x) => hex2bin($x),
        fn ($x) => gzinflate($x),
    )($string);
}

$string = 'Hello World!';

$encoded = encodeString($string);
$decoded = decodeString($encoded);

var_dump($string, $encoded, $decoded);
string(12) "Hello World!"
string(28) "f348cdc9c95708cf2fca49510400"
string(12) "Hello World!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment