diff --git a/src/Database/Attach/File.php b/src/Database/Attach/File.php index 5ecf7b5a1..ccaba0dfe 100644 --- a/src/Database/Attach/File.php +++ b/src/Database/Attach/File.php @@ -10,6 +10,7 @@ use Illuminate\Support\Facades\Storage; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\File as FileObj; +use Winter\Storm\Exception\ApplicationException; /** * File attachment model @@ -141,6 +142,29 @@ public function fromFile($filePath) return $this; } + /** + * Creates a file object from a file on the disk returned by $this->getDisk() + */ + public function fromStorage(string $filePath): static + { + $disk = $this->getDisk(); + + if (!$disk->exists($filePath)) { + throw new \InvalidArgumentException(sprintf('File `%s` was not found on the storage disk', $filePath)); + } + + $this->file_name = basename($filePath); + $this->file_size = $disk->size($filePath); + $this->content_type = $disk->mimeType($filePath); + $this->disk_name = $this->getDiskName(); + + if (!$disk->copy($filePath, $this->getDiskPath())) { + throw new ApplicationException(sprintf('Unable to copy `%s` to `%s`', $filePath, $this->getDiskPath())); + } + + return $this; + } + /** * Creates a file object from raw data. * @@ -529,8 +553,10 @@ public function beforeSave() if ($this->data !== null) { if ($this->data instanceof UploadedFile) { $this->fromPost($this->data); - } else { + } elseif (file_exists($this->data)) { $this->fromFile($this->data); + } else { + $this->fromStorage($this->data); } $this->data = null;