2022-09-20 19:59:52 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Rules;
|
|
|
|
|
|
|
|
use App\Http\Controllers\Forms\PublicFormController;
|
|
|
|
use App\Service\Storage\StorageFileNameParser;
|
|
|
|
use Illuminate\Contracts\Validation\Rule;
|
|
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
use Illuminate\Support\Str;
|
2023-04-26 15:05:02 +00:00
|
|
|
use App\Models\Forms\Form;
|
2022-09-20 19:59:52 +00:00
|
|
|
|
|
|
|
class StorageFile implements Rule
|
|
|
|
{
|
|
|
|
public int $maxSize;
|
|
|
|
|
|
|
|
public string $error = 'Invalid file.';
|
|
|
|
|
|
|
|
/** @var string[] */
|
|
|
|
public array $fileTypes;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param int $maxSize
|
|
|
|
* @param string[] $fileTypes
|
|
|
|
*/
|
2023-04-26 15:05:02 +00:00
|
|
|
public function __construct(int $maxSize, array $fileTypes = [], public ?Form $form = null)
|
2022-09-20 19:59:52 +00:00
|
|
|
{
|
|
|
|
$this->maxSize = $maxSize;
|
|
|
|
|
|
|
|
$this->fileTypes = $fileTypes;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* File can have 2 formats:
|
|
|
|
* - file_name-{uuid}.{ext}
|
|
|
|
* - {uuid}
|
|
|
|
*
|
|
|
|
* @param string $attribute
|
|
|
|
* @param mixed $value
|
|
|
|
* @return bool
|
|
|
|
*/
|
|
|
|
public function passes($attribute, $value): bool
|
|
|
|
{
|
2023-10-20 09:00:35 +00:00
|
|
|
// If full path then no need to validate
|
|
|
|
if (filter_var($value, FILTER_VALIDATE_URL) !== FALSE) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2023-04-26 15:05:02 +00:00
|
|
|
// This is use when updating a record, and file uploads aren't changed.
|
|
|
|
if($this->form){
|
|
|
|
$newPath = Str::of(PublicFormController::FILE_UPLOAD_PATH)->replace('?', $this->form->id);
|
2023-08-16 08:59:07 +00:00
|
|
|
if(Storage::exists($newPath.'/'.$value)){
|
2023-04-26 15:05:02 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-20 19:59:52 +00:00
|
|
|
$fileNameParser = StorageFileNameParser::parse($value);
|
|
|
|
if (!$uuid = $fileNameParser->uuid) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
$filePath = PublicFormController::TMP_FILE_UPLOAD_PATH.$uuid;
|
|
|
|
if (!Storage::exists($filePath)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Storage::size($filePath) > $this->maxSize) {
|
|
|
|
$this->error = 'File is too large.';
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (count($this->fileTypes) > 0) {
|
|
|
|
$this->error = 'Incorrect file type. Allowed only: '.implode(",", $this->fileTypes);
|
|
|
|
return in_array($fileNameParser->extension, $this->fileTypes);
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function message(): string
|
|
|
|
{
|
|
|
|
return $this->error;
|
|
|
|
}
|
|
|
|
}
|