ldc-groupe/app/Traits/Requests/HasInertiaPicture.php
2026-02-13 12:10:35 +01:00

120 lines
4.1 KiB
PHP

<?php
namespace App\Traits\Requests;
use Illuminate\Http\UploadedFile;
trait HasInertiaPicture
{
/**
* Prepare the data for validation.
*
* @return void
*/
protected function mergeInertiaPicture(): void
{
if (empty($this->convertedFiles)) {
return;
}
$original = $this->all();
$merged = self::arrayMergeRecursiveDistinct($original, $this->convertedFiles);
$this->replace($merged);
}
/**
* Merge recursive data.
*
* @param array $array1
* @param array $array2
* @return array
*/
protected static function arrayMergeRecursiveDistinct(array $array1, array $array2): array
{
$merged = $array1;
foreach ($array2 as $key => $value) {
if (isset($merged[$key]) && is_array($merged[$key]) && is_array($value)) {
$merged[$key] = self::arrayMergeRecursiveDistinct($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
/**
* Set picture rules (UploadedFile or string path).
*
* @param string $rules
* @return array<mixed>
*/
protected function pictureRules(string $rules): array
{
$rules = explode("|", $rules);
return [
function ($attribute, $value, $fail) use ($rules) {
$isRequired = in_array('required', $rules);
$isNullable = in_array('nullable', $rules);
// Check required value.
if ($isRequired && $value === null) {
$label = $this->attributes()[$attribute] ?? $attribute;
$fail(trans('validation.required', ['attribute' => $label]));
return;
}
// Authorized nullable value.
if ($isNullable && $value === null) {
return;
}
// UploadedFile validations.
if ($value instanceof UploadedFile) {
// Filter unused rules for validator.
// The “required” and “nullable” rules are not the same as those for online validation.
$validatorRules = array_filter($rules, fn($r) => $r !== 'required' && $r !== 'nullable');
$validator = \Validator::make(
[$attribute => $value],
[$attribute => implode('|', $validatorRules)]
);
if ($validator->fails()) {
$fail($validator->errors()->first($attribute));
}
return;
}
// String path validations.
if (is_string($value)) {
// Validate the path.
// phpcs:ignore Generic.Files.LineLength
$pattern = '/^storage\/modelfiles\/[a-zA-Z0-9_]+\/[0-9]{2}\/[0-9]{2}\/[0-9]{2}\/[a-zA-Z0-9]{2}\/[a-zA-Z0-9_-]+/';
if (!preg_match($pattern, $value)) {
$fail(trans('validation.file_path', ['attribute' => $this->attributes()[$attribute]]));
return;
}
// Validate the extension.
$mimesRule = collect($rules)->first(fn($r) => str_starts_with($r, 'mimes:'));
if ($mimesRule) {
$allowedExtensions = explode(',', str_replace('mimes:', '', $mimesRule));
$ext = strtolower(pathinfo($value, PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExtensions)) {
$fail(trans('validation.mimetypes', [
'attribute' => $this->attributes()[$attribute],
'values' => implode(', ', $allowedExtensions),
]));
}
}
return;
} //end if
// Unmanaged case (not null, not UploadedFile, not string).
$fail("Invalide type for $attribute.");
}
];
}
}