Skip to content

Commit

Permalink
rollback the action of saving files when there's an exception
Browse files Browse the repository at this point in the history
  • Loading branch information
kolirt committed Oct 26, 2024
1 parent 64109b8 commit d2add82
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 20 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
56 changes: 37 additions & 19 deletions src/Traits/MasterModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
/**
Expand Down Expand Up @@ -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 = [];
Expand All @@ -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([
Expand All @@ -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);
}


}

0 comments on commit d2add82

Please sign in to comment.