|
2 | 2 |
|
3 | 3 | namespace Illuminate\Routing;
|
4 | 4 |
|
| 5 | +use Closure; |
5 | 6 | use Illuminate\Contracts\Routing\ResponseFactory as FactoryContract;
|
6 | 7 | use Illuminate\Contracts\View\Factory as ViewFactory;
|
7 | 8 | use Illuminate\Http\JsonResponse;
|
8 | 9 | use Illuminate\Http\Response;
|
9 | 10 | use Illuminate\Routing\Exceptions\StreamedResponseException;
|
| 11 | +use Illuminate\Support\Js; |
10 | 12 | use Illuminate\Support\Str;
|
11 | 13 | use Illuminate\Support\Traits\Macroable;
|
12 | 14 | use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
@@ -117,6 +119,47 @@ public function jsonp($callback, $data = [], $status = 200, array $headers = [],
|
117 | 119 | return $this->json($data, $status, $headers, $options)->setCallback($callback);
|
118 | 120 | }
|
119 | 121 |
|
| 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 | + |
120 | 163 | /**
|
121 | 164 | * Create a new streamed response instance.
|
122 | 165 | *
|
|
0 commit comments