diff --git a/src/Illuminate/Http/StreamedEvent.php b/src/Illuminate/Http/StreamedEvent.php new file mode 100644 index 000000000000..e6defe52f8ee --- /dev/null +++ b/src/Illuminate/Http/StreamedEvent.php @@ -0,0 +1,27 @@ +event = $event; + $this->data = $data; + } +} diff --git a/src/Illuminate/Routing/ResponseFactory.php b/src/Illuminate/Routing/ResponseFactory.php index 200ed11a075c..7886a0a43243 100644 --- a/src/Illuminate/Routing/ResponseFactory.php +++ b/src/Illuminate/Routing/ResponseFactory.php @@ -7,6 +7,7 @@ use Illuminate\Contracts\View\Factory as ViewFactory; use Illuminate\Http\JsonResponse; use Illuminate\Http\Response; +use Illuminate\Http\StreamedEvent; use Illuminate\Routing\Exceptions\StreamedResponseException; use Illuminate\Support\Js; use Illuminate\Support\Str; @@ -124,10 +125,10 @@ public function jsonp($callback, $data = [], $status = 200, array $headers = [], * * @param \Closure $callback * @param array $headers - * @param string $endStreamWith + * @param \Illuminate\Http\StreamedEvent|string $endStreamWith * @return \Symfony\Component\HttpFoundation\StreamedResponse */ - public function eventStream(Closure $callback, array $headers = [], string $endStreamWith = '') + public function eventStream(Closure $callback, array $headers = [], StreamedEvent|string|null $endStreamWith = '') { return $this->stream(function () use ($callback, $endStreamWith) { foreach ($callback() as $message) { @@ -135,11 +136,18 @@ public function eventStream(Closure $callback, array $headers = [], string $endS break; } + $event = 'update'; + + if ($message instanceof StreamedEvent) { + $event = $message->event; + $message = $message->data; + } + if (! is_string($message) && ! is_numeric($message)) { $message = Js::encode($message); } - echo "event: update\n"; + echo "event: $event\n"; echo 'data: '.$message; echo "\n\n"; @@ -147,12 +155,21 @@ public function eventStream(Closure $callback, array $headers = [], string $endS flush(); } - echo "event: update\n"; - echo 'data: '.$endStreamWith; - echo "\n\n"; + if (filled($endStreamWith)) { + $endEvent = 'update'; + + if ($endStreamWith instanceof StreamedEvent) { + $endEvent = $endStreamWith->event; + $endStreamWith = $endStreamWith->data; + } + + echo "event: $endEvent\n"; + echo 'data: '.$endStreamWith; + echo "\n\n"; - ob_flush(); - flush(); + ob_flush(); + flush(); + } }, 200, array_merge($headers, [ 'Content-Type' => 'text/event-stream', 'Cache-Control' => 'no-cache',