Passed
Pull Request — master (#3)
by PHPinnacle
03:21
created

SignalDispatcher::handler()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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