Skip to content

Commit

Permalink
fix zipping
Browse files Browse the repository at this point in the history
  • Loading branch information
QuentinGab committed Jan 23, 2024
1 parent 1853a78 commit 1556573
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
40 changes: 32 additions & 8 deletions src/MediaZipper.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Support\Collection;
use Symfony\Component\HttpFoundation\StreamedResponse;
use ZipStream\OperationMode;
use ZipStream\ZipStream;

class MediaZipper implements Responsable
Expand All @@ -23,10 +24,12 @@ public function toFile(Filesystem $storage, string $path, array $options = []):
{
$temporaryStream = fopen('php://memory', 'w+');

$this->getZipStream([
$zip = $this->getZipStream([
'outputStream' => $temporaryStream,
]);

$zip->finish();

$success = $storage->writeStream($path, $temporaryStream, $options);

fclose($temporaryStream);
Expand All @@ -36,10 +39,10 @@ public function toFile(Filesystem $storage, string $path, array $options = []):

public function getZipStream(array $options = [])
{
$zip = new ZipStream(
...$this->zipStreamOptions,
...$options,
);
$zip = new ZipStream(...array_merge(
$this->zipStreamOptions,
$options
));

/** @var Media $item */
foreach ($this->media as $index => $item) {
Expand All @@ -56,16 +59,37 @@ public function getZipStream(array $options = [])
}
}

$zip->finish();

return $zip;
}

public function getSize(): int
{
return (int) $this->media->sum('size');
}

public function toResponse($request): StreamedResponse
{
return new StreamedResponse(fn () => $this->getZipStream(), 200, [
$simulation = $this->getZipStream([
'defaultEnableZeroHeader' => true,
'sendHttpHeaders' => false,
'contentType' => 'application/octet-stream',
'operationMode' => OperationMode::SIMULATE_STRICT, // or SIMULATE_LAX
]);

$size = $simulation->finish();

return new StreamedResponse(function () {
$zip = $this->getZipStream([
'defaultEnableZeroHeader' => true,
'contentType' => 'application/octet-stream',
]);

$zip->finish();

}, 200, [
'Content-Disposition' => "attachment; filename=\"{$this->fileName}\"",
'Content-Type' => 'application/octet-stream',
'Content-Length' => $size,
]);
}
}
2 changes: 1 addition & 1 deletion src/Traits/InteractsWithMediaFiles.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
/**
* @property ?string $disk
* @property ?string $path
* @property ?int $size
* @property ?int $size The filesize in bytes
* @property ?float $duration in miliseconds
*/
trait InteractsWithMediaFiles
Expand Down

0 comments on commit 1556573

Please sign in to comment.