Passed
Pull Request — master (#9)
by Shinji
01:19
created

AsyncLoopBuilder::addProcess()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 6
c 1
b 0
f 1
nc 2
nop 2
dl 0
loc 9
rs 10
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
namespace PhpProfiler\Lib\Loop;
13
14
use LogicException;
15
16
final class AsyncLoopBuilder
17
{
18
    /** @var array<int, class-string<AsyncLoopMiddlewareInterface>> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<int, class-string<...opMiddlewareInterface>> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<int, class-string<AsyncLoopMiddlewareInterface>>.
Loading history...
19
    private array $process_stack = [];
20
    /** @var array<int, array> */
21
    private array $parameter_stack = [];
22
23
    /**
24
     * @param class-string<AsyncLoopMiddlewareInterface> $process
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<AsyncLoopMiddlewareInterface> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<AsyncLoopMiddlewareInterface>.
Loading history...
25
     * @param array $parameters
26
     * @return self
27
     */
28
    public function addProcess(string $process, array $parameters): self
29
    {
30
        if (!is_a($process, AsyncLoopMiddlewareInterface::class, true)) {
31
            throw new LogicException('1st argument must be a name of a class implements LoopMiddlewareInterface');
32
        }
33
        $self = clone $this;
34
        $self->process_stack[] = $process;
35
        $self->parameter_stack[] = $parameters;
36
        return $self;
37
    }
38
39
    public function build(): AsyncLoop
40
    {
41
        $process = null;
42
        $stack_num = count($this->process_stack);
43
        for ($i = $stack_num - 1; $i >= 0; $i--) {
44
            $parameters = $this->parameter_stack[$i];
45
            if (!is_null($process)) {
46
                $parameters[] = $process;
47
            }
48
            $loop_class_name = $this->process_stack[$i];
49
            $process = new $loop_class_name(...$parameters);
50
        }
51
        if (is_null($process)) {
52
            throw new LogicException('no LoopProcess specified');
53
        }
54
        return new AsyncLoop($process);
55
    }
56
}
57