71 lines
2.2 KiB
PHP
71 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Requests\Back\Recipes;
|
|
|
|
use App\Lib\Helpers\ToolboxHelper;
|
|
use Illuminate\Http\UploadedFile;
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class UpdateRecipeRequest extends StoreRecipeRequest
|
|
{
|
|
/**
|
|
* Get the validation rules that apply to the request.
|
|
*
|
|
* @return array<string, \Illuminate\Validation\Rule|array<mixed>|string>
|
|
*/
|
|
public function rules(): array
|
|
{
|
|
return array_merge(parent::rules(), [
|
|
'picture' => [
|
|
'required',
|
|
$this->validatePicture(...),
|
|
],
|
|
]);
|
|
}
|
|
|
|
private function validatePicture(string $attribute, mixed $value, \Closure $fail): void
|
|
{
|
|
$valuePath = match (true) {
|
|
is_string($value) => $value,
|
|
$value instanceof UploadedFile => $value->getPathname(),
|
|
default => null
|
|
};
|
|
|
|
if (is_string($valuePath)) {
|
|
$this->validateMaxFileSize($attribute, $valuePath, $fail);
|
|
|
|
ToolboxHelper::validatePicture(
|
|
$attribute,
|
|
$valuePath,
|
|
$fail,
|
|
(object) [
|
|
'minWidth' => self::PICTURE_WIDTH,
|
|
'maxWidth' => self::PICTURE_WIDTH,
|
|
'minHeight' => self::PICTURE_HEIGHT,
|
|
'maxHeight' => self::PICTURE_HEIGHT,
|
|
]
|
|
);
|
|
} elseif ($value !== null) {
|
|
$fail('Unexpected value for picture');
|
|
}
|
|
}
|
|
|
|
private function validateMaxFileSize(string $attribute, string $valuePath, \Closure $fail): void
|
|
{
|
|
$sizeInBytes = match (true) {
|
|
Storage::exists($valuePath) => Storage::size($valuePath),
|
|
File::exists($valuePath) => File::size($valuePath),
|
|
default => 0,
|
|
};
|
|
|
|
if (($sizeInBytes / 1024) > self::MAX_FILE_SIZE_KB) {
|
|
$fail(trans('validation.max.file', [
|
|
'attribute' => $this->attributes()[$attribute] ?? $attribute,
|
|
'max' => self::MAX_FILE_SIZE_KB,
|
|
]));
|
|
}
|
|
}
|
|
}
|