Passed
Pull Request — master (#8)
by Shinji
08:28
created

LoopBuilder::addProcess()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 9
rs 10
c 2
b 0
f 2
1
<?php
2
3
/**
4
 * This file is part of the sj-i/php-profiler package.
5
 *
6
 * (c) sji <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace PhpProfiler\Lib\Loop;
15
16
use LogicException;
17
18
final class LoopBuilder
19
{
20
    /** @var array<int, class-string<LoopProcessInterface>> */
1 ignored issue
show
Documentation Bug introduced by
The doc comment array<int, class-string<LoopProcessInterface>> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<int, class-string<LoopProcessInterface>>.
Loading history...
21
    private array $process_stack = [];
22
    /** @var array<int, array> */
23
    private array $parameter_stack = [];
24
25
    /**
26
     * @param class-string<LoopProcessInterface> $process
1 ignored issue
show
Documentation Bug introduced by
The doc comment class-string<LoopProcessInterface> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<LoopProcessInterface>.
Loading history...
27
     * @param array $parameters
28
     * @return self
29
     */
30
    public function addProcess(string $process, array $parameters): self
31
    {
32
        if (!is_a($process, LoopProcessInterface::class, true)) {
33
            throw new LogicException('1st argument must be a name of a class implements LoopProcessInterface');
34
        }
35
        $self = clone $this;
36
        $self->process_stack[] = $process;
37
        $self->parameter_stack[] = $parameters;
38
        return $self;
39
    }
40
41
    public function build(): Loop
42
    {
43
        $process = null;
44
        $stack_num = count($this->process_stack);
45
        for ($i = $stack_num - 1; $i >= 0; $i--) {
46
            $parameters = $this->parameter_stack[$i];
47
            if (!is_null($process)) {
48
                $parameters[] = $process;
49
            }
50
            $loop_class_name = $this->process_stack[$i];
51
            $process = new $loop_class_name(...$parameters);
52
        }
53
        if (is_null($process)) {
54
            throw new LogicException('no LoopProcess specified');
55
        }
56
        return new Loop($process);
57
    }
58
}
59