ServerSentEvent.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpClient\Chunk;
  11. use Symfony\Contracts\HttpClient\ChunkInterface;
  12. /**
  13. * @author Antoine Bluchet <soyuka@gmail.com>
  14. * @author Nicolas Grekas <p@tchwork.com>
  15. */
  16. final class ServerSentEvent extends DataChunk implements ChunkInterface
  17. {
  18. private $data = '';
  19. private $id = '';
  20. private $type = 'message';
  21. private $retry = 0;
  22. public function __construct(string $content)
  23. {
  24. parent::__construct(-1, $content);
  25. // remove BOM
  26. if (0 === strpos($content, "\xEF\xBB\xBF")) {
  27. $content = substr($content, 3);
  28. }
  29. foreach (preg_split("/(?:\r\n|[\r\n])/", $content) as $line) {
  30. if (0 === $i = strpos($line, ':')) {
  31. continue;
  32. }
  33. $i = false === $i ? \strlen($line) : $i;
  34. $field = substr($line, 0, $i);
  35. $i += 1 + (' ' === ($line[1 + $i] ?? ''));
  36. switch ($field) {
  37. case 'id': $this->id = substr($line, $i); break;
  38. case 'event': $this->type = substr($line, $i); break;
  39. case 'data': $this->data .= ('' === $this->data ? '' : "\n").substr($line, $i); break;
  40. case 'retry':
  41. $retry = substr($line, $i);
  42. if ('' !== $retry && \strlen($retry) === strspn($retry, '0123456789')) {
  43. $this->retry = $retry / 1000.0;
  44. }
  45. break;
  46. }
  47. }
  48. }
  49. public function getId(): string
  50. {
  51. return $this->id;
  52. }
  53. public function getType(): string
  54. {
  55. return $this->type;
  56. }
  57. public function getData(): string
  58. {
  59. return $this->data;
  60. }
  61. public function getRetry(): float
  62. {
  63. return $this->retry;
  64. }
  65. }