-
-
Notifications
You must be signed in to change notification settings - Fork 307
Expand file tree
/
Copy pathEventStreamResponse.php
More file actions
110 lines (96 loc) · 2.88 KB
/
EventStreamResponse.php
File metadata and controls
110 lines (96 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation;
/**
* Represents a streaming HTTP response for sending server events
* as part of the Server-Sent Events (SSE) streaming technique.
*
* To broadcast events to multiple users at once, for long-running
* connections and for high-traffic websites, prefer using the Mercure
* Symfony Component, which relies on Software designed for these use
* cases: https://symfony.com/doc/current/mercure.html
*
* @see ServerEvent
*
* @author Yonel Ceruto <open@yceruto.dev>
*
* Example usage:
*
* return new EventStreamResponse(function () {
* yield new ServerEvent(time());
*
* sleep(1);
*
* yield new ServerEvent(time());
* });
*/
class EventStreamResponse extends StreamedResponse
{
/**
* @param int|null $retry The number of milliseconds the client should wait
* before reconnecting in case of network failure
*/
public function __construct(?callable $callback = null, int $status = 200, array $headers = [], private ?int $retry = null)
{
$headers += [
'Connection' => 'keep-alive',
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'private, no-cache, no-store, must-revalidate, max-age=0',
'X-Accel-Buffering' => 'no',
'Pragma' => 'no-cache',
'Expires' => '0',
];
parent::__construct($callback, $status, $headers);
}
public function setCallback(callable $callback): static
{
if ($this->callback) {
return parent::setCallback($callback);
}
$this->callback = function () use ($callback) {
if (is_iterable($events = $callback($this))) {
foreach ($events as $event) {
$this->sendEvent($event);
if (connection_aborted()) {
break;
}
}
}
};
return $this;
}
/**
* Sends a server event to the client.
*
* @return $this
*/
public function sendEvent(ServerEvent $event): static
{
if ($this->retry > 0 && !$event->getRetry()) {
$event->setRetry($this->retry);
}
foreach ($event as $part) {
echo $part;
if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
static::closeOutputBuffers(0, true);
flush();
}
}
return $this;
}
public function getRetry(): ?int
{
return $this->retry;
}
public function setRetry(int $retry): void
{
$this->retry = $retry;
}
}