diff --git a/composer.json b/composer.json index ccee4b8..b8e70e0 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ ], "homepage": "https://github.com/kolirt/laravel-master-model", "license": "MIT", - "version": "4.0.5", + "version": "4.0.6", "authors": [ { "name": "kolirt" diff --git a/src/Traits/MasterModel.php b/src/Traits/MasterModel.php index 125420b..f472d9f 100644 --- a/src/Traits/MasterModel.php +++ b/src/Traits/MasterModel.php @@ -12,6 +12,18 @@ trait MasterModel protected array $saved_files = []; protected array $files_to_delete = []; + public function responseFile(string $key, $name = null, array $headers = [], $disposition = 'inline') + { + $value = $this->getAttributeValue($key); + + if (is_stored_file($value)) { + [$disk_name, $stored_file_path] = explode(':', $value); + return Storage::disk($disk_name)->response($stored_file_path, $name, $headers, $disposition); + } + + abort(404); + } + public function delete(): ?bool { $need_delete = false; @@ -188,7 +200,15 @@ public function save(array $options = []) } } - $saved = parent::save($options); + try { + $saved = parent::save($options); + } catch (\Exception $e) { + /** + * Rollback the action of saving files + */ + $this->revertSavingFiles(); + throw $e; + } if ($saved) { /** @@ -344,12 +364,9 @@ public function save(array $options = []) } } else { /** - * Rollback saved files + * Rollback the action of saving files */ - foreach ($this->saved_files as $file) { - Storage::disk($file['disk'])->delete($file['value']); - $this->setAttribute($file['key'], $file['old_value']); - } + $this->revertSavingFiles(); } $this->relations_to_save = []; @@ -359,6 +376,20 @@ public function save(array $options = []) return $saved; } + /** + * Rollback the action of saving files + */ + private function revertSavingFiles(): void + { + /** + * Rollback saved files + */ + foreach ($this->saved_files as $file) { + Storage::disk($file['disk'])->delete($file['value']); + $this->setAttribute($file['key'], $file['old_value']); + } + } + private function getUploadFolder($key): string { return collect([ @@ -373,17 +404,4 @@ private function getDisk($key = null): string return $this->upload_disks[$key] ?? config('master-model.files.disk'); } - public function responseFile(string $key, $name = null, array $headers = [], $disposition = 'inline') - { - $value = $this->getAttributeValue($key); - - if (is_stored_file($value)) { - [$disk_name, $stored_file_path] = explode(':', $value); - return Storage::disk($disk_name)->response($stored_file_path, $name, $headers, $disposition); - } - - abort(404); - } - - }