Restore missed original file only on check the file existing

This commit is contained in:
Yuriy Bakhtin 2023-08-04 12:47:25 +02:00
parent e3975394c0
commit 2b47ac9ebd
2 changed files with 18 additions and 8 deletions

View File

@ -188,7 +188,7 @@ class DownloadAction extends Action
*/
protected function checkFileExists()
{
if (!file_exists($this->file->store->get($this->variant))) {
if (!$this->file->store->has($this->variant)) {
throw new HttpException(404, Yii::t('FileModule.base', 'Could not find requested file!'));
}
}

View File

@ -50,7 +50,16 @@ class StorageManager extends Component implements StorageManagerInterface
*/
public function has($variant = null): bool
{
return file_exists($this->get($variant));
if (file_exists($this->get($variant))) {
return true;
}
if ($variant === null) {
// Try to restore only original file
return $this->restoreMissedOriginalFile();
}
return false;
}
/**
@ -60,7 +69,6 @@ class StorageManager extends Component implements StorageManagerInterface
{
if ($variant === null) {
$variant = $this->originalFileName;
$this->restoreMissedOriginalFile();
}
return $this->getPath() . DIRECTORY_SEPARATOR . $variant;
@ -68,25 +76,27 @@ class StorageManager extends Component implements StorageManagerInterface
/**
* Restore original file from the latest version if it was missed by some reason
*
* @return bool TRUE if original file is restored successfully or if it already exists
*/
protected function restoreMissedOriginalFile()
protected function restoreMissedOriginalFile(): bool
{
$originalFilePath = $this->getPath() . DIRECTORY_SEPARATOR . $this->originalFileName;
if (file_exists($originalFilePath)) {
// Original File exists as expected, nothing to restore
return;
return true;
}
$latestHistoryFile = $this->file->getHistoryFiles()->limit(1)->one();
if (!$latestHistoryFile instanceof FileHistory) {
// File has no any history version, impossible to restore
return;
return false;
}
// Copy the latest version to original File path
copy($latestHistoryFile->getFileStorePath(), $originalFilePath);
@chmod($originalFilePath, $this->fileMode);
return copy($latestHistoryFile->getFileStorePath(), $originalFilePath) &&
@chmod($originalFilePath, $this->fileMode);
}
/**