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 | use Amp\Promise; |
||
16 | |||
17 | final class DispatcherBuilder |
||
18 | { |
||
19 | /** |
||
20 | * @var HandlerFactory |
||
21 | */ |
||
22 | private $factory; |
||
23 | |||
24 | /** |
||
25 | * @var callable[][] |
||
26 | */ |
||
27 | private $handlers = []; |
||
28 | |||
29 | /** |
||
30 | * @param HandlerFactory $factory |
||
31 | */ |
||
32 | 2 | public function __construct(HandlerFactory $factory = null) |
|
33 | { |
||
34 | 2 | $this->factory = $factory ?: new HandlerFactory; |
|
35 | 2 | } |
|
36 | |||
37 | /** |
||
38 | * @param string $signal |
||
39 | * @param callable $handler |
||
40 | * |
||
41 | * @return self |
||
42 | */ |
||
43 | 2 | public function register(string $signal, callable $handler): self |
|
44 | { |
||
45 | 2 | $this->handlers[$signal][] = $handler; |
|
46 | |||
47 | 2 | return $this; |
|
48 | } |
||
49 | |||
50 | /** |
||
51 | * @return Dispatcher |
||
52 | */ |
||
53 | 2 | public function build(): Dispatcher |
|
54 | { |
||
55 | 2 | $registry = new HandlerRegistry; |
|
56 | |||
57 | 2 | foreach ($this->handlers as $signal => $handlers) { |
|
58 | $handlers = \array_map(function (callable $handler) { |
||
59 | 2 | return $this->factory->create($handler); |
|
60 | 2 | }, $handlers); |
|
61 | |||
62 | $registry->add($signal, static function (...$arguments) use ($handlers) { |
||
63 | 2 | $promises = []; |
|
64 | |||
65 | 2 | foreach ($handlers as $handler) { |
|
66 | 2 | $promises[] = yield $handler => $arguments; |
|
67 | } |
||
68 | |||
69 | 2 | return \count($promises) === 1 ? \current($promises) : Promise\all($promises); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
70 | 2 | }); |
|
71 | } |
||
72 | |||
73 | 2 | return new Dispatcher($registry); |
|
74 | } |
||
75 | } |
||
76 |