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

Dispatcher   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 48
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 2
A dispatch() 0 13 2
A register() 0 6 1
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