Passed
Push — master ( 2f01ca...ac7767 )
by PHPinnacle
06:39
created

SignalDispatcher::handler()   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
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 2
eloc 1
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 HandlerMap
19
     */
20
    private $handlers;
21
22
    /**
23
     * @param HandlerMap $handlers
24
     */
25 4
    public function __construct(HandlerMap $handlers)
26
    {
27 4
        $this->handlers = $handlers;
28 4
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 3
    public function dispatch(string $signal, ...$arguments): Task
34
    {
35 3
        $handler = $this->handler($signal);
36 3
        $channel = Channel::open($signal);
37
38 3
        $promise = \future(function () use ($channel, $handler, $arguments) {
39 3
            $result = $handler(...$arguments);
40
41 2
            if ($result instanceof \Generator) {
42 1
                $result = \coroutine($channel->attach($result));
43
            }
44
45 2
            return $result;
46 3
        });
47
48 3
        return new Task($promise, $channel);
49
    }
50
51
    /**
52
     * @param string $signal
53
     *
54
     * @return Handler
55
     */
56 3
    private function handler(string $signal): Handler
57
    {
58 3
        return $this->handlers->get($signal) ?: Handler::unknown($signal);
59
    }
60
}
61