108 lines
3.3 KiB
PHP
108 lines
3.3 KiB
PHP
<?php
|
|
|
|
namespace App\Traits\Requests;
|
|
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
|
|
trait HasDocumentAndPictureList
|
|
{
|
|
/**
|
|
* Autorised mimtypes
|
|
*
|
|
* @var string[]
|
|
*/
|
|
private $autorisedMimTypes = [
|
|
'application/msword',
|
|
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
'image/jpeg',
|
|
'image/png',
|
|
'image/gif',
|
|
'application/pdf',
|
|
'application/vnd.ms-powerpoint',
|
|
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
'application/vnd.ms-excel',
|
|
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
'text/csv',
|
|
'text/plain',
|
|
];
|
|
|
|
/**
|
|
* Images rules
|
|
*
|
|
* @param string $name
|
|
* @return array
|
|
*/
|
|
public function documentsRules(
|
|
string $name = 'docs',
|
|
): array {
|
|
return [
|
|
"{$name}" => 'present|array',
|
|
"{$name}.*" => [
|
|
'required',
|
|
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)
|
|
{
|
|
// phpcs:enable
|
|
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), $this->autorisedMimTypes)) {
|
|
$fail(trans(':attribute doit être un document de type :mimetypes', [
|
|
'mimetypes' => Str::of($this->autorisedMimTypes)->implode(' ou ')
|
|
]));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Merges docs fields with request data.
|
|
*
|
|
* @param string $name
|
|
* @return void
|
|
*/
|
|
protected function mergeDocuments(string $name = 'docs'): void
|
|
{
|
|
$documents = $this->{$name};
|
|
$this->merge([$name => $this->{$name} ?? []]);
|
|
$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
|
|
}
|
|
}
|