ldc-groupe/app/Traits/Requests/HasInertiaPicture.php
2025-10-17 14:53:09 +02:00

64 lines
2.3 KiB
PHP

<?php
namespace App\Traits\Requests;
trait HasInertiaPicture
{
/**
* Prepare the data for validation.
*
* @param string $field
* @return void
*/
protected function mergeInertiaPicture(string $field = 'content'): void
{
// Si rien à merger (convertedFiles est null ou ne contient pas le champ), on return en douceur
if (empty($this->convertedFiles) || empty($this->convertedFiles[$field])) {
return;
}
$converted = $this->convertedFiles[$field]; // Ce qu'on veut merger
// Si l'input du champ n'existe pas, on le crée avec converted
if (!$this->has($field)) {
$this->merge([$field => $converted]);
return;
}
// Si l'input existe et que converted a aussi des données => merge récursif
$original = $this->input($field);
// On vérifie que les deux sont bien des tableaux (sinon array_merge_recursive plantera dans le bueno)
if (!is_array($original)) {
$original = [$original];
}
if (!is_array($converted)) {
$converted = [$converted];
}
$merged = array_merge_recursive($original, $converted);
$this->merge([$field => $merged]);
}
protected function pictureRules(string $field = "picture", string $rules)
{
if (is_string($this->$field) && (\request()->method() === "PUT")) {
$isNullable = \strpos($rules, 'nullable');
$extensions = explode("|", explode("|mimes:", $rules)[1])[0];
$allowedExtensions = explode(',', $extensions); // Ex: "jpg,png" → ['jpg', 'png']
return [
$isNullable ? 'nullable' : 'required',
'string',
'regex:/^storage\/modelfiles\/+[a-zA-Z0-9_]*\/+[0-9]{2}\/+[0-9]{2}\/+[0-9]{2}\/+[a-zA-Z0-9]{2}\/+[a-zA-Z0-9_-]*/',
function ($attribute, $value, $fail) use ($allowedExtensions) {
$extension = pathinfo($value, PATHINFO_EXTENSION);
if (!in_array(strtolower($extension), $allowedExtensions)) {
$fail("Le fichier doit avoir une extension valide : " . implode(', ', $allowedExtensions));
}
}
];
}
return $rules;
}
}