Skip to content

Commit

Permalink
adds TemporaryFile
Browse files Browse the repository at this point in the history
  • Loading branch information
cosmastech committed Sep 15, 2023
1 parent 16115ca commit eee3ac7
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions src/Support/TemporaryFile.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace Spatie\MediaLibrary\Support;

use Illuminate\Support\Str;
use Spatie\MediaLibrary\MediaCollections\Filesystem;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\Support\TemporaryDirectory as SupportTemporaryDirectory;
use Spatie\TemporaryDirectory\TemporaryDirectory;

class TemporaryFile
{
protected string $file;

protected TemporaryDirectory $temporaryDirectory;

protected Media $media;

public function __construct(Media $media)
{
$this->media = $media;
}

public function getFile(): string
{
if (! isset($this->file)) {
$this->copyFile();
}

return $this->file;
}

protected function copyFile(): void
{
if (! isset($this->temporaryDirectory)) {
$this->createTemporaryDirectory();
}

$this->file = app(Filesystem::class)->copyFromMediaLibrary(
$this->media,
$this->temporaryDirectory->path(Str::random(32) . '.' . $this->media->extension)
);
}

protected function createTemporaryDirectory(): void
{
$this->temporaryDirectory = SupportTemporaryDirectory::create();
}

public function __destruct()
{
if (isset($this->temporaryDirectory)) {
$this->temporaryDirectory->delete();
}
}
}

0 comments on commit eee3ac7

Please sign in to comment.