Passed
Push — master ( 5627de...230c64 )
by PHPinnacle
02:25
created

Dispatcher::dispatch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 13
ccs 8
cts 8
cp 1
crap 2
rs 10
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
final class Dispatcher implements Contract\Dispatcher
16
{
17
    /**
18
     * @var Processor
19
     */
20
    private $processor;
21
22
    /**
23
     * @var callable[]
24
     */
25
    private $handlers = [];
26
27
    /**
28
     * @param Processor $processor
29
     */
30 6
    public function __construct(Processor $processor = null)
31
    {
32 6
        $this->processor = $processor ?: new Processor();
33 6
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 5
    public function register(string $signal, callable $handler): void
39
    {
40 5
        $this->handlers[$signal] = $handler;
41
42 5
        $this->processor->interrupt($signal, function (...$arguments) use ($signal) {
43 1
            return $this->dispatch($signal, ...$arguments);
44 5
        });
45 5
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 6
    public function dispatch($signal, ...$arguments): Task
51
    {
52 6
        if (\is_object($signal)) {
53 1
            \array_unshift($arguments, $signal);
54
55 1
            $signal = \get_class($signal);
56
        }
57
58 6
        $handler = $this->handlers[$signal] ?? static function () use ($signal) {
59 1
            throw new Exception\UnknownSignal($signal);
60 6
        };
61
62 6
        return $this->processor->execute($handler, $arguments);
63
    }
64
}
65