ServerSentEvents.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. declare(strict_types=1);
  15. namespace Workerman\Protocols\Http;
  16. use function str_replace;
  17. /**
  18. * Class ServerSentEvents
  19. * @package Workerman\Protocols\Http
  20. */
  21. class ServerSentEvents
  22. {
  23. /**
  24. * Data.
  25. * @var array
  26. */
  27. protected array $data;
  28. /**
  29. * ServerSentEvents constructor.
  30. * $data for example ['event'=>'ping', 'data' => 'some thing', 'id' => 1000, 'retry' => 5000]
  31. * @param array $data
  32. */
  33. public function __construct(array $data)
  34. {
  35. $this->data = $data;
  36. }
  37. /**
  38. * __toString.
  39. *
  40. * @return string
  41. */
  42. public function __toString()
  43. {
  44. $buffer = '';
  45. $data = $this->data;
  46. if (isset($data[''])) {
  47. $buffer = ": {$data['']}\n";
  48. }
  49. if (isset($data['event'])) {
  50. $buffer .= "event: {$data['event']}\n";
  51. }
  52. if (isset($data['id'])) {
  53. $buffer .= "id: {$data['id']}\n";
  54. }
  55. if (isset($data['retry'])) {
  56. $buffer .= "retry: {$data['retry']}\n";
  57. }
  58. if (isset($data['data'])) {
  59. $buffer .= 'data: ' . str_replace("\n", "\ndata: ", $data['data']) . "\n";
  60. }
  61. return $buffer . "\n";
  62. }
  63. }