| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\HttpFoundation; |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
class EventStreamResponse extends StreamedResponse |
| 38 |
{ |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
public function __construct(?callable $callback = null, int $status = 200, array $headers = [], private ?int $retry = null) |
| 44 |
{ |
| 45 |
$headers += [ |
| 46 |
'Connection' => 'keep-alive', |
| 47 |
'Content-Type' => 'text/event-stream', |
| 48 |
'Cache-Control' => 'private, no-cache, no-store, must-revalidate, max-age=0', |
| 49 |
'X-Accel-Buffering' => 'no', |
| 50 |
'Pragma' => 'no-cache', |
| 51 |
'Expires' => '0', |
| 52 |
]; |
| 53 |
|
| 54 |
parent::__construct($callback, $status, $headers); |
| 55 |
} |
| 56 |
|
| 57 |
public function setCallback(callable $callback): static |
| 58 |
{ |
| 59 |
if ($this->callback) { |
| 60 |
return parent::setCallback($callback); |
| 61 |
} |
| 62 |
|
| 63 |
$this->callback = function () use ($callback) { |
| 64 |
if (is_iterable($events = $callback($this))) { |
| 65 |
foreach ($events as $event) { |
| 66 |
$this->sendEvent($event); |
| 67 |
|
| 68 |
if (connection_aborted()) { |
| 69 |
break; |
| 70 |
} |
| 71 |
} |
| 72 |
} |
| 73 |
}; |
| 74 |
|
| 75 |
return $this; |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
public function sendEvent(ServerEvent $event): static |
| 84 |
{ |
| 85 |
if ($this->retry > 0 && !$event->getRetry()) { |
| 86 |
$event->setRetry($this->retry); |
| 87 |
} |
| 88 |
|
| 89 |
foreach ($event as $part) { |
| 90 |
echo $part; |
| 91 |
|
| 92 |
if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) { |
| 93 |
static::closeOutputBuffers(0, true); |
| 94 |
flush(); |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
return $this; |
| 99 |
} |
| 100 |
|
| 101 |
public function getRetry(): ?int |
| 102 |
{ |
| 103 |
return $this->retry; |
| 104 |
} |
| 105 |
|
| 106 |
public function setRetry(int $retry): void |
| 107 |
{ |
| 108 |
$this->retry = $retry; |
| 109 |
} |
| 110 |
} |