123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- class Handler {
- private $parsedown;
- public function __construct() {
- $this->parsedown = new Parsedown();
- }
- public function handle(object $json, $from, WebSocketHandler $ws) {
- if (!isset($json->action)) {
- throw new HandlerException("Error processing request", 1);
- }
- if (!isset($json->data)) {
- $json->data = null;
- }
- if (!method_exists($this, $json->action)) {
- throw new HandlerException("Error action not found", 2);
- }
- call_user_func_array([$this, $json->action], [$ws, $from, $json->data]);
- }
- public function info(WebSocketHandler $ws, $from) {
- $data = ['id' => $from->resourceId, 'gm' => ($ws->countClients() == 1)];
- $from->send($this->encode($data));
- }
- public function markdown(WebSocketHandler $ws, $from, $data) {
- $data = ['md' => $this->parsedown->text($data)];
- $from->send($this->encode($data));
- }
- public function to_player(WebSocketHandler $ws, $from, $data) {
- $ws->forEachClients(function ($client) use ($data) {
- if ($client->resourceId !== $data->gm) {
- $client->send(json_encode($data));
- }
- });
- }
- public function to_gm(WebSocketHandler $ws, $from, $data) {
- $ws->forOneClient($data->gm, function ($client) use ($data) {
- $client->send(json_encode($data));
- });
- }
- public function to_other(WebSocketHandler $ws, $from, $data) {
- $ws->forEachClients(function ($client) use ($from, $data) {
- if ($from->resourceId !== $client->resourceId) {
- $client->send(json_encode($data));
- }
- });
- }
- private function encode($data, bool $success = true) {
- $status = $success ? 'ok' : 'err';
- return json_encode(['status' => $status, 'data' => $data]);
- }
- }
- class HandlerException extends Exception {
- public function __construct($message = "", $code = 0, Throwable $previous = null) {
- parent::__construct($message, $code, $previous);
- }
- }
|