Core\Response\Stream::end
$stream->end(): voidEnds a response body that Core\Response::startStream started. The client receives the end of the body at once. Your program can go on running after end(), but it cannot write to the body again. A write() after end() throws a LogicError. Calling end() a second time does nothing.
Without end(), the body ends when the program ends. A stream started with the $mustEnd argument is different. Its body is complete only after end(). If the program stops before that, the body is cut off, so the browser shows a failed download. The error log then names the stream with the $mustEnd value. Use $mustEnd for a file download, where a part that is missing makes the whole file useless.
The examples end a download, end a body before more work, and end a body with a known length.
Return value
Returns void. Nothing. A stream started with $mustEnd needs this call, or the body is cut off when the program stops. A write() after end() throws an error.
Examples
End a download
<?nvs// Shows a download that is complete only after `end()`.
// The fourth argument, `$mustEnd`, is the name the error log uses if the program never calls `end()`.Core\Response\Stream $body = Core\Response::startStream('text/csv', null, null, 'orders.csv');$body->write("id,total\n");$body->write("1042,19.90\n");
// `end()` ends the body. Without this call, the download is cut off.$body->end();id,total1042,19.90End before more work
<?nvs// Shows that the program can go on running after `end()`.
Core\Response\Stream $body = Core\Response::startStream('text/plain; charset=utf-8');$body->write("Your report is ready.\n");
// The client receives the end of the body now and does not wait for the work below.$body->end();
// This work runs after the client has the whole body.// The log record goes to standard error, so it is the last line of the output.array<int> $values = [3, 4, 5];int $total = 0;foreach ($values as int $value) { $total = $total + $value;}Core\Log::write(Core\Log::Level::Info, 'report sent', ['total' => $total]);// proof: with-stderrYour report is ready.{"level":"info","msg":"report sent","source":{"file":"docs/examples/core/Response-Stream/end/02-end-before-more-work.nvs","line":17},"fields":{"total":12}}A body with a length
<?nvs// Shows `end()` on a body with a known length.
// The body is 5 bytes long, so the response has the header `Content-Length: 5`.Core\Response\Stream $body = Core\Response::startStream('text/plain; charset=utf-8', 5);$body->write('Hello');
// All 5 bytes are written, so `end()` ends a complete body.$body->end();Hello