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

Dispatcher::instance()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
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
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