Code

< 40 %
40-60 %
> 60 %
1
<?php
2
3
namespace SRIO\ChainOfResponsibility;
4
5
class ChainRunner extends ProcessCollection
6
{
7
    /**
8
     * @var DecoratorFactoryInterface
9
     */
10
    private $decoratorFactory;
11
12
    /**
13
     * @param ChainProcessInterface[]        $processes
14
     * @param DecoratorFactoryInterface|null $decoratorFactory
15
     */
16 8
    public function __construct(array $processes, DecoratorFactoryInterface $decoratorFactory = null)
17
    {
18 8
        $this->decoratorFactory = $decoratorFactory !== null ? $decoratorFactory : new DecoratorFactory();
19 8
        $this->add($processes);
20 8
    }
21
22
    /**
23
     * @param ChainContext $context
24
     *
25
     * @return ChainContext
26
     */
27 8
    public function run(ChainContext $context = null)
28
    {
29 8
        if (null === $context) {
30 7
            $context = new ArrayChainContext();
31 7
        }
32
33 8
        $this->getHead()->execute($context);
34
35 7
        return $context;
36
    }
37
38
    /**
39
     * @return ChainProcessInterface
40
     */
41 8
    public function getHead()
42
    {
43 8
        return $this->getDecoratedProcesses()[0];
44
    }
45
46
    /**
47
     * @return ChainProcessInterface[]
48
     */
49 8
    public function getDecoratedProcesses()
50
    {
51 8
        $processes = $this->getProcesses();
52 8
        $numberOfProcesses = count($processes);
53 8
        if ($numberOfProcesses === 0) {
54 1
            throw new \RuntimeException('You must have at least one process to run');
55
        }
56
57 7
        $decoratedProcesses = [];
58 7
        $next = null;
59
60 7
        for ($i = $numberOfProcesses - 1; $i >= 0; --$i) {
61 7
            $decoratedProcesses[$i] = $next = $this->decoratorFactory->decorate($processes[$i], $next);
62 7
        }
63
64 7
        return $decoratedProcesses;
65
    }
66
}
67