pipe.php ➔ pipe()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 12
nc 1
nop 1
dl 0
loc 20
ccs 11
cts 11
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Prelude;
4
5
use function Prelude\tail;
6
7
const pipe = '\pipe';
8
9
/**
10
 * Performs left-to-right function composition.
11
 * The leftmost function may have any arity; the remaining functions must be unary.
12
 */
13
function pipe(callable ...$callbacks): \Closure
14
{
15
    return function ($payload = null, ...$rest) use ($callbacks) {
16
        $leftmost = function ($payload) use ($rest, $callbacks) {
17 2
            return $callbacks[0](
18 2
                ...\array_merge([$payload], $rest)
19
            );
20 6
        };
21
22 6
        return \array_reduce(
23 6
            [] === $rest
24 4
                ? $callbacks
25 6
                : \array_merge([$leftmost], tail($callbacks)),
26
            function ($payload, callable $callback) {
27 6
                return $callback($payload);
28 6
            },
29 6
            $payload
30
        );
31 6
    };
32
}
33