Skip to content

Commit

Permalink
Created getConversionStream helper method (#3501)
Browse files Browse the repository at this point in the history
Replaced fpassthru with feof/fread with variable chunk size

Co-authored-by: Chris Page <[email protected]>
  • Loading branch information
chrispage1 and chrispage1 authored Jan 5, 2024
1 parent 978bd61 commit 7b4ccb7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/MediaCollections/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,13 @@ public function getStream(Media $media)
return $this->filesystem->disk($media->disk)->readStream($sourceFile);
}

public function getConversionStream(Media $media, string $conversion)
{
$sourceFile = $media->getPathRelativeToRoot($conversion);

return $this->filesystem->disk($media->conversions_disk)->readStream($sourceFile);
}

public function copyFromMediaLibrary(Media $media, string $targetFile): string
{
file_put_contents($targetFile, $this->getStream($media));
Expand Down
14 changes: 13 additions & 1 deletion src/MediaCollections/Models/Media.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ class Media extends Model implements Attachable, Htmlable, Responsable
'responsive_images' => 'array',
];

protected int $streamChunkSize = (1024 * 1024); // default to 1MB chunks.

public function newCollection(array $models = [])
{
return new MediaCollection($models);
Expand Down Expand Up @@ -303,6 +305,13 @@ public function hasGeneratedConversion(string $conversionName): bool
return $generatedConversions[$conversionName] ?? false;
}

public function setStreamChunkSize(int $chunkSize)
{
$this->streamChunkSize = $chunkSize;

return $this;
}

public function toResponse($request)
{
return $this->buildResponse($request, 'attachment');
Expand All @@ -326,7 +335,10 @@ private function buildResponse($request, string $contentDispositionType)
return response()->stream(function () {
$stream = $this->stream();

fpassthru($stream);
while(!feof($stream)) {
echo fread($stream, $this->streamChunkSize);
flush();
}

if (is_resource($stream)) {
fclose($stream);
Expand Down

0 comments on commit 7b4ccb7

Please sign in to comment.