1
0
mirror of https://github.com/BookStackApp/BookStack.git synced 2025-08-07 23:03:00 +03:00

Range requests: Extracted stream output handling to new class

This commit is contained in:
Dan Brown
2024-01-07 14:03:13 +00:00
parent b191d8f99f
commit b4d9029dc3
4 changed files with 80 additions and 28 deletions

View File

@@ -9,11 +9,9 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
class DownloadResponseFactory
{
protected Request $request;
public function __construct(Request $request)
{
$this->request = $request;
public function __construct(
protected Request $request
) {
}
/**
@@ -27,19 +25,11 @@ class DownloadResponseFactory
/**
* Create a response that forces a download, from a given stream of content.
*/
public function streamedDirectly($stream, string $fileName): StreamedResponse
public function streamedDirectly($stream, string $fileName, int $fileSize): StreamedResponse
{
return response()->stream(function () use ($stream) {
// End & flush the output buffer, if we're in one, otherwise we still use memory.
// Output buffer may or may not exist depending on PHP `output_buffering` setting.
// Ignore in testing since output buffers are used to gather a response.
if (!empty(ob_get_status()) && !app()->runningUnitTests()) {
ob_end_clean();
}
fpassthru($stream);
fclose($stream);
$rangeStream = new RangeSupportedStream($stream, $fileSize, $this->request->headers);
return response()->stream(function () use ($rangeStream) {
$rangeStream->outputAndClose();
}, 200, $this->getHeaders($fileName));
}
@@ -48,15 +38,13 @@ class DownloadResponseFactory
* correct for the file, in a way so the browser can show the content in browser,
* for a given content stream.
*/
public function streamedInline($stream, string $fileName): StreamedResponse
public function streamedInline($stream, string $fileName, int $fileSize): StreamedResponse
{
$sniffContent = fread($stream, 2000);
$mime = (new WebSafeMimeSniffer())->sniff($sniffContent);
$rangeStream = new RangeSupportedStream($stream, $fileSize, $this->request->headers);
$mime = $rangeStream->sniffMime();
return response()->stream(function () use ($sniffContent, $stream) {
echo $sniffContent;
fpassthru($stream);
fclose($stream);
return response()->stream(function () use ($rangeStream) {
$rangeStream->outputAndClose();
}, 200, $this->getHeaders($fileName, $mime));
}