Skip to content

Instantly share code, notes, and snippets.

@azerum
Created July 24, 2021 19:42
Show Gist options
  • Select an option

  • Save azerum/29d27eaa7b53c6c23d42ad94423f0883 to your computer and use it in GitHub Desktop.

Select an option

Save azerum/29d27eaa7b53c6c23d42ad94423f0883 to your computer and use it in GitHub Desktop.
Chain functions with signature 'function($value, callable $next)' in PHP
<?php
function pipeline(callable ...$pipes) {
$pipes_count = count($pipes);
if ($pipes_count === 0) {
return;
}
$last_pipe = $pipes[$pipes_count - 1];
$other_pipes = array_slice($pipes, 0, $pipes_count - 1);
return array_reduce(
array_reverse($other_pipes),
function($previous_pipe, $pipe) {
return function($value) use ($previous_pipe, $pipe) {
return $pipe($value, $previous_pipe);
};
},
$last_pipe
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment