Created
July 24, 2021 19:42
-
-
Save azerum/29d27eaa7b53c6c23d42ad94423f0883 to your computer and use it in GitHub Desktop.
Chain functions with signature 'function($value, callable $next)' in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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