-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
16115ca
commit eee3ac7
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
} |