Passed
Push — master ( 904700...0f63fa )
by PHPinnacle
05:59 queued 03:40
created

Dispatcher   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A dispatch() 0 13 2
A __construct() 0 3 2
A register() 0 9 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
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
     * @param string   $signal
37
     * @param callable $handler
38
     *
39
     * @return self
40
     */
41 5
    public function register(string $signal, callable $handler): self
42
    {
43 5
        $this->handlers[$signal] = $handler;
44
45 5
        $this->processor->interrupt($signal, function (...$arguments) use ($signal) {
46 1
            return $this->dispatch($signal, ...$arguments);
47 5
        });
48
49 5
        return $this;
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55 6
    public function dispatch($signal, ...$arguments): Task
56
    {
57 6
        if (\is_object($signal)) {
58 1
            \array_unshift($arguments, $signal);
59
60 1
            $signal = \get_class($signal);
61
        }
62
63 6
        $handler = $this->handlers[$signal] ?? function () use ($signal) {
64 1
            throw new Exception\UnknownSignal($signal);
65 6
        };
66
67 6
        return $this->processor->execute($handler, $arguments);
68
    }
69
}
70