DispatcherBuilder::build()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 2
nop 0
dl 0
loc 21
ccs 11
cts 11
cp 1
crap 4
rs 9.9
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of PHPinnacle/Ensign.
4
 *
5
 * (c) PHPinnacle Team <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types = 1);
12
13
namespace PHPinnacle\Ensign;
14
15
use Amp\Promise;
16
17
final class DispatcherBuilder
18
{
19
    /**
20
     * @var HandlerFactory
21
     */
22
    private $factory;
23
24
    /**
25
     * @var callable[][]
26
     */
27
    private $handlers = [];
28
29
    /**
30
     * @param HandlerFactory $factory
31
     */
32 2
    public function __construct(HandlerFactory $factory = null)
33
    {
34 2
        $this->factory = $factory ?: new HandlerFactory;
35 2
    }
36
37
    /**
38
     * @param string   $signal
39
     * @param callable $handler
40
     *
41
     * @return self
42
     */
43 2
    public function register(string $signal, callable $handler): self
44
    {
45 2
        $this->handlers[$signal][] = $handler;
46
47 2
        return $this;
48
    }
49
50
    /**
51
     * @return Dispatcher
52
     */
53 2
    public function build(): Dispatcher
54
    {
55 2
        $registry = new HandlerRegistry;
56
57 2
        foreach ($this->handlers as $signal => $handlers) {
58
            $handlers = \array_map(function (callable $handler) {
59 2
                return $this->factory->create($handler);
60 2
            }, $handlers);
61
62
            $registry->add($signal, static function (...$arguments) use ($handlers) {
63 2
                $promises = [];
64
65 2
                foreach ($handlers as $handler) {
66 2
                    $promises[] = yield $handler => $arguments;
67
                }
68
69 2
                return \count($promises) === 1 ? \current($promises) : Promise\all($promises);
0 ignored issues
show
Bug introduced by
The function all was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

69
                return \count($promises) === 1 ? \current($promises) : /** @scrutinizer ignore-call */ Promise\all($promises);
Loading history...
70 2
            });
71
        }
72
73 2
        return new Dispatcher($registry);
74
    }
75
}
76