90 lines
2.7 KiB
PHP
90 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Traits\Requests;
|
|
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
trait HasDocument
|
|
{
|
|
/**
|
|
* Images rules
|
|
*
|
|
* @param string $name
|
|
* @param boolean $required
|
|
* @return array
|
|
*/
|
|
public function documentsRules(
|
|
string $name = 'documents',
|
|
?bool $required = null
|
|
): array {
|
|
return [
|
|
"{$name}" => ($required ? 'required' : 'nullable') . '|array',
|
|
"{$name}.*" => [
|
|
$required ? 'required' : 'nullable',
|
|
function (string $attribute, $value, callable $fail) {
|
|
return $this->validateDocument($attribute, $value, $fail);
|
|
}
|
|
]
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Validate picture.
|
|
*
|
|
* @param string $attribute
|
|
* @param mixed $value
|
|
* @param callback $fail
|
|
* @return void
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed
|
|
*/
|
|
private function validateDocument(string $attribute, mixed $value, callable $fail)
|
|
{
|
|
if (!($useStorage = Storage::exists($value)) and !File::exists($value)) {
|
|
$fail(trans(":attribute n'existe pas dans le système de fichier"));
|
|
return;
|
|
}
|
|
if (
|
|
!\in_array($this->getUploadedFileMimeType($value, $useStorage), [
|
|
'application/pdf'
|
|
])
|
|
) {
|
|
$fail(trans(":attribute doit être une image de type 'application/pdf'"));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Merges documents fields with request data.
|
|
*
|
|
* @param string $name
|
|
* @return void
|
|
*/
|
|
protected function mergeDocuments(string $name = 'documents'): void
|
|
{
|
|
$documents = $this->{$name};
|
|
$this->merge(['doc' => $this->docs ?? []]);
|
|
$this->merge(["{$name}Validate" => []]);
|
|
if (is_array($documents)) {
|
|
foreach ($documents as $key => $documentPath) {
|
|
// ! Empty document.
|
|
if ($documentPath === 'false') {
|
|
// * Empty document and exit
|
|
$this->merge([$name => []]);
|
|
return;
|
|
}
|
|
$decodedPath = \urldecode($documentPath);
|
|
$this->merge([
|
|
"{$name}Validate" => array_merge(
|
|
$this->{"{$name}Validate"},
|
|
[\public_path(ltrim($decodedPath, '/'))]
|
|
)
|
|
]);
|
|
$changedDocument = $this->{$name};
|
|
$changedDocument[$key] = ltrim($decodedPath, '/');
|
|
$this->merge([
|
|
$name => $changedDocument
|
|
]);
|
|
}
|
|
} //end if
|
|
}
|
|
}
|