ldc-legaulois/app/Http/Requests/UpdateMiniCrudRequest.php
2021-09-20 16:17:32 +02:00

102 lines
3.7 KiB
PHP

<?php
namespace App\Http\Requests;
use App\Enums\InputType;
use App\Lib\Utils;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
abstract class UpdateMiniCrudRequest extends FormRequest
{
/** The model parameter name */
protected $modelName = null;
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [];
foreach ($this->{$this->modelName}->data as $iptName => $input) {
switch ($input['inputType']['value']) {
case InputType::string()->value:
$rules = array_merge($rules, [
"data.$iptName.value" => 'required|string|min:4'
]);
break;
case InputType::text()->value:
$rules = array_merge($rules, [
"data.$iptName.value" => 'required|string|min:15'
]);
break;
case InputType::image()->value:
$ipt = $this->data[$iptName];
$max = isset($ipt['dimensionsMax']);
$dim = collect(explode(
',',
$ipt['dimensionsMax'] ?? $input['dimensions']
))->mapWithKeys(function ($v) {
$v = explode(' ', $v);
return [$v[0] => $v[1]];
});
$rules = array_merge($rules, [
"data.$iptName.value" => [
'sometimes',
'image',
'mimes:png,jpg,svg',
sprintf(
'dimensions:%s=%d,%s=%d',
$max ? 'max_height' : 'height',
$dim['hauteur'],
$max ? 'max_width' : 'width',
$dim['largeur']
)
]
]);
break;
case InputType::url()->value:
$rules = array_merge($rules, [
"data.$iptName.value" => [
'required', 'url',
// @phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
function ($attribute, $value, $fail) {
try {
Utils::assertNoInternalUrls($attribute, $value);
} catch (ValidationException $e) {
$fail(collect($e->errors())->first()[0]);
}
}
]
]);
break;
case InputType::boolean()->value:
$all = $this->all();
$nested = Utils::dotStringToNestedArray(
"data.$iptName.value",
$this->input("data.$iptName.value") ? true : false
);
$all = array_merge_recursive_distinct($all, $nested);
$this->merge($all);
$rules = array_merge($rules, [
"data.$iptName.value" => 'boolean'
]);
break;
}
}
return $rules;
}
}