ServerSentEvents.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. namespace Workerman\Protocols\Http;
  15. /**
  16. * Class ServerSentEvents
  17. * @package Workerman\Protocols\Http
  18. */
  19. class ServerSentEvents
  20. {
  21. /**
  22. * Data.
  23. * @var array
  24. */
  25. protected $_data = null;
  26. /**
  27. * ServerSentEvents constructor.
  28. * $data for example ['event'=>'ping', 'data' => 'some thing', 'id' => 1000, 'retry' => 5000]
  29. * @param array $data
  30. */
  31. public function __construct(array $data)
  32. {
  33. $this->_data = $data;
  34. }
  35. /**
  36. * __toString.
  37. *
  38. * @return string
  39. */
  40. public function __toString()
  41. {
  42. $buffer = '';
  43. $data = $this->_data;
  44. if (isset($data[''])) {
  45. $buffer = ": {$data['']}\n";
  46. }
  47. if (isset($data['event'])) {
  48. $buffer .= "event: {$data['event']}\n";
  49. }
  50. if (isset($data['data'])) {
  51. $buffer .= 'data: ' . \str_replace("\n", "\ndata: ", $data['data']) . "\n\n";
  52. }
  53. if (isset($data['id'])) {
  54. $buffer .= "id: {$data['id']}\n";
  55. }
  56. if (isset($data['retry'])) {
  57. $buffer .= "retry: {$data['retry']}\n";
  58. }
  59. return $buffer;
  60. }
  61. }