Skip to content

Commit ec94a5a

Browse files
committed
Add Response::eventStream
1 parent 99c179b commit ec94a5a

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/Illuminate/Routing/ResponseFactory.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22

33
namespace Illuminate\Routing;
44

5+
use Closure;
56
use Illuminate\Contracts\Routing\ResponseFactory as FactoryContract;
67
use Illuminate\Contracts\View\Factory as ViewFactory;
78
use Illuminate\Http\JsonResponse;
89
use Illuminate\Http\Response;
910
use Illuminate\Routing\Exceptions\StreamedResponseException;
11+
use Illuminate\Support\Js;
1012
use Illuminate\Support\Str;
1113
use Illuminate\Support\Traits\Macroable;
1214
use Symfony\Component\HttpFoundation\BinaryFileResponse;
@@ -117,6 +119,47 @@ public function jsonp($callback, $data = [], $status = 200, array $headers = [],
117119
return $this->json($data, $status, $headers, $options)->setCallback($callback);
118120
}
119121

122+
/**
123+
* Create a new event stream response.
124+
*
125+
* @param \Closure $callback
126+
* @param array $headers
127+
* @param string $endStreamWith
128+
* @return \Symfony\Component\HttpFoundation\StreamedResponse
129+
*/
130+
public function eventStream(Closure $callback, array $headers = [], string $endStreamWith = '</stream>')
131+
{
132+
return $this->stream(function () use ($callback, $endStreamWith) {
133+
foreach ($callback() as $message) {
134+
if (connection_aborted()) {
135+
break;
136+
}
137+
138+
if (! is_string($message) && ! is_numeric($message)) {
139+
$message = Js::encode($message);
140+
}
141+
142+
echo "event: update\n";
143+
echo 'data: '.$message;
144+
echo "\n\n";
145+
146+
ob_flush();
147+
flush();
148+
}
149+
150+
echo "event: update\n";
151+
echo 'data: '.$endStreamWith;
152+
echo "\n\n";
153+
154+
ob_flush();
155+
flush();
156+
}, 200, array_merge($headers, [
157+
'Content-Type' => 'text/event-stream',
158+
'Cache-Control' => 'no-cache',
159+
'X-Accel-Buffering' => 'no',
160+
]));
161+
}
162+
120163
/**
121164
* Create a new streamed response instance.
122165
*

0 commit comments

Comments
 (0)