Completed
Push — master ( 753c96...c3156c )
by Sébastien
01:47
created

StackProcessor::buildCallable()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 2
nop 2
1
<?php
2
3
namespace Bdf\Pipeline\Processor;
4
5
use Bdf\Pipeline\ProcessorInterface;
6
7
/**
8
 * StackProcessor
9
 *
10
 * @author Sébastien Tanneux
11
 */
12
class StackProcessor implements ProcessorInterface
13
{
14
    /**
15
     * The pipes callable
16
     *
17
     * @var callable
18
     */
19
    private $callable;
20
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public function process(array $pipes, array $payload, callable $outlet = null)
25
    {
26
        if ($this->callable === null) {
27
            $this->callable = $this->buildCallable($pipes, $outlet);
28
        }
29
30
        $callable = $this->callable;
31
32
        return $callable(...$payload);
33
    }
34
35
    /**
36
     * Build the chain callable
37
     *
38
     * @param array $pipes
39
     * @param callable|null $outlet
40
     *
41
     * @return \Closure
42
     */
43
    private function buildCallable($pipes, $outlet)
44
    {
45
        $callable = function (...$payload) use($outlet) {
46
            if ($outlet !== null) {
47
                return $outlet(...$payload);
48
            }
49
50
            return $payload[0] ?? null;
51
        };
52
53
        while ($pipe = array_pop($pipes)) {
54
            $callable = function (...$payload) use ($pipe, $callable) {
55
                return $pipe($callable, ...$payload);
56
            };
57
        }
58
59
        return $callable;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function clearCache()
66
    {
67
        $this->callable = null;
68
    }
69
}
70