Handler.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. class Handler {
  3. private $parsedown;
  4. public function __construct() {
  5. $this->parsedown = new Parsedown();
  6. }
  7. public function handle(object $json, $from, WebSocketHandler $ws) {
  8. if (!isset($json->action)) {
  9. throw new HandlerException("Error processing request", 1);
  10. }
  11. if (!isset($json->data)) {
  12. $json->data = null;
  13. }
  14. if (!method_exists($this, $json->action)) {
  15. throw new HandlerException("Error action not found", 2);
  16. }
  17. call_user_func_array([$this, $json->action], [$ws, $from, $json->data]);
  18. }
  19. public function info(WebSocketHandler $ws, $from) {
  20. $data = ['id' => $from->resourceId, 'gm' => ($ws->countClients() == 1)];
  21. $from->send($this->encode($data));
  22. }
  23. public function markdown(WebSocketHandler $ws, $from, $data) {
  24. $data = ['md' => $this->parsedown->text($data)];
  25. $from->send($this->encode($data));
  26. }
  27. public function to_player(WebSocketHandler $ws, $from, $data) {
  28. $ws->forEachClients(function ($client) use ($data) {
  29. if ($client->resourceId !== $data->gm) {
  30. $client->send(json_encode($data));
  31. }
  32. });
  33. }
  34. public function to_gm(WebSocketHandler $ws, $from, $data) {
  35. $ws->forOneClient($data->gm, function ($client) use ($data) {
  36. $client->send(json_encode($data));
  37. });
  38. }
  39. public function to_other(WebSocketHandler $ws, $from, $data) {
  40. $ws->forEachClients(function ($client) use ($from, $data) {
  41. if ($from->resourceId !== $client->resourceId) {
  42. $client->send(json_encode($data));
  43. }
  44. });
  45. }
  46. private function encode($data, bool $success = true) {
  47. $status = $success ? 'ok' : 'err';
  48. return json_encode(['status' => $status, 'data' => $data]);
  49. }
  50. }
  51. class HandlerException extends Exception {
  52. public function __construct($message = "", $code = 0, Throwable $previous = null) {
  53. parent::__construct($message, $code, $previous);
  54. }
  55. }