1 | <?php |
||
13 | class Subscriber implements SubscriberContract |
||
14 | { |
||
15 | /** |
||
16 | * The logger instance. |
||
17 | * |
||
18 | * @var LoggerContract |
||
19 | */ |
||
20 | protected $logger; |
||
21 | |||
22 | /** |
||
23 | * The dispatcher instance. |
||
24 | * |
||
25 | * @var DispatcherContract |
||
26 | */ |
||
27 | protected $dispatcher; |
||
28 | |||
29 | /** |
||
30 | * The event mappings. |
||
31 | * |
||
32 | * @var array |
||
33 | */ |
||
34 | protected $events; |
||
35 | |||
36 | /** |
||
37 | * Create a new subscriber instance. |
||
38 | * |
||
39 | * @param LoggerContract $logger |
||
40 | * @param DispatcherContract $dispatcher |
||
41 | * @param array $events |
||
42 | */ |
||
43 | 16 | public function __construct(LoggerContract $logger, DispatcherContract $dispatcher, array $events) |
|
49 | |||
50 | /** |
||
51 | * Handle the connect event. |
||
52 | * |
||
53 | * @param WebSocket $webSocket |
||
54 | * |
||
55 | * @return void |
||
56 | */ |
||
57 | 2 | public function onConnect(WebSocket $webSocket): void |
|
72 | |||
73 | /** |
||
74 | * Handle the message event. |
||
75 | * |
||
76 | * @param MessageContract $message |
||
77 | * |
||
78 | * @return void |
||
79 | */ |
||
80 | 4 | public function onMessage(MessageContract $message): void |
|
81 | { |
||
82 | 4 | $payload = json_decode($message->getPayload()); |
|
83 | |||
84 | 4 | $this->logger->info('websocket message', compact('payload')); |
|
85 | |||
86 | 4 | if (!isset($payload->type) || !isset($this->events[$payload->type])) { |
|
87 | 2 | return; |
|
88 | } |
||
89 | |||
90 | 2 | $this->dispatcher->dispatch(new $this->events[$payload->type]($payload)); |
|
91 | 2 | } |
|
92 | |||
93 | /** |
||
94 | * Handle the disconnect event. |
||
95 | * |
||
96 | * @param int|null $code |
||
97 | * @param string|null $reason |
||
98 | * |
||
99 | * @return void |
||
100 | */ |
||
101 | 2 | public function onDisconnect(int $code = null, string $reason = null): void |
|
105 | |||
106 | /** |
||
107 | * Handle the error event. |
||
108 | * |
||
109 | * @param Exception $exception |
||
110 | * |
||
111 | * @return void |
||
112 | */ |
||
113 | 2 | public function onError(Exception $exception): void |
|
117 | |||
118 | /** |
||
119 | * Register the listeners for the subscriber. |
||
120 | * |
||
121 | * @param PromiseContract $connection |
||
122 | */ |
||
123 | 2 | public function subscribe(PromiseContract $connection): void |
|
127 | } |
||
128 |