Skip to content

Commit cc1a3e8

Browse files
[11.x] Enhance eventStream to Support Custom Events and Start Messages (#54695)
* feat: add support for optional event stream start and end tokens * feat: support customizing the event stream name * style: follow formatting style in phpdoc * fix: add missing $as use declaration * formatting --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent bd278a7 commit cc1a3e8

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

src/Illuminate/Routing/ResponseFactory.php

+22-9
Original file line numberDiff line numberDiff line change
@@ -124,12 +124,23 @@ public function jsonp($callback, $data = [], $status = 200, array $headers = [],
124124
*
125125
* @param \Closure $callback
126126
* @param array $headers
127-
* @param string $endStreamWith
127+
* @param string $as
128+
* @param string|null $startStreamWith
129+
* @param string|null $endStreamWith
128130
* @return \Symfony\Component\HttpFoundation\StreamedResponse
129131
*/
130-
public function eventStream(Closure $callback, array $headers = [], string $endStreamWith = '</stream>')
132+
public function eventStream(Closure $callback, array $headers = [], string $as = 'update', ?string $startStreamWith = null, ?string $endStreamWith = '</stream>')
131133
{
132-
return $this->stream(function () use ($callback, $endStreamWith) {
134+
return $this->stream(function () use ($callback, $as, $startStreamWith, $endStreamWith) {
135+
if (filled($startStreamWith)) {
136+
echo "event: $as\n";
137+
echo 'data: '.$startStreamWith;
138+
echo "\n\n";
139+
140+
ob_flush();
141+
flush();
142+
}
143+
133144
foreach ($callback() as $message) {
134145
if (connection_aborted()) {
135146
break;
@@ -139,20 +150,22 @@ public function eventStream(Closure $callback, array $headers = [], string $endS
139150
$message = Js::encode($message);
140151
}
141152

142-
echo "event: update\n";
153+
echo "event: $as\n";
143154
echo 'data: '.$message;
144155
echo "\n\n";
145156

146157
ob_flush();
147158
flush();
148159
}
149160

150-
echo "event: update\n";
151-
echo 'data: '.$endStreamWith;
152-
echo "\n\n";
161+
if (filled($endStreamWith)) {
162+
echo "event: $as\n";
163+
echo 'data: '.$endStreamWith;
164+
echo "\n\n";
153165

154-
ob_flush();
155-
flush();
166+
ob_flush();
167+
flush();
168+
}
156169
}, 200, array_merge($headers, [
157170
'Content-Type' => 'text/event-stream',
158171
'Cache-Control' => 'no-cache',

0 commit comments

Comments
 (0)