Message.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * Copyright (C) 2014-2022 Textalk/Abicart and contributors.
  4. *
  5. * This file is part of Websocket PHP and is free software under the ISC License.
  6. * License text: https://raw.githubusercontent.com/Textalk/websocket-php/master/COPYING
  7. */
  8. namespace WebSocket\Message;
  9. use DateTime;
  10. abstract class Message
  11. {
  12. protected $opcode;
  13. protected $payload;
  14. protected $timestamp;
  15. public function __construct(string $payload = '')
  16. {
  17. $this->payload = $payload;
  18. $this->timestamp = new DateTime();
  19. }
  20. public function getOpcode(): string
  21. {
  22. return $this->opcode;
  23. }
  24. public function getLength(): int
  25. {
  26. return strlen($this->payload);
  27. }
  28. public function getTimestamp(): DateTime
  29. {
  30. return $this->timestamp;
  31. }
  32. public function getContent(): string
  33. {
  34. return $this->payload;
  35. }
  36. public function setContent(string $payload = ''): void
  37. {
  38. $this->payload = $payload;
  39. }
  40. public function hasContent(): bool
  41. {
  42. return $this->payload != '';
  43. }
  44. public function __toString(): string
  45. {
  46. return get_class($this);
  47. }
  48. // Split messages into frames
  49. public function getFrames(bool $masked = true, int $framesize = 4096): array
  50. {
  51. $frames = [];
  52. $split = str_split($this->getContent(), $framesize) ?: [''];
  53. foreach ($split as $payload) {
  54. $frames[] = [false, $payload, 'continuation', $masked];
  55. }
  56. $frames[0][2] = $this->opcode;
  57. $frames[array_key_last($frames)][0] = true;
  58. return $frames;
  59. }
  60. }