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

SignalDispatcher   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 49
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A dispatch() 0 9 2
A register() 0 8 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 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