ldc-cocotte/app/Http/Requests/Bo/Employees/ImportRequest.php

104 lines
3.2 KiB
PHP
Raw Normal View History

2026-06-14 21:32:07 +02:00
<?php
declare(strict_types=1);
namespace App\Http\Requests\Bo\Employees;
use App\Lib\Helpers\StringEncoder;
use Domain\Models\ValueObjects\CsvImportFile;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\UploadedFile;
use Infrastructure\Adapters\Services\AppAdminAuthService;
class ImportRequest extends FormRequest
{
private ?CsvImportFile $importedFile = null;
public function __construct(
private readonly AppAdminAuthService $authService
) {
}
public function authorize(): bool
{
return $this->authService->check();
}
public function getSalarieImportFile(): CsvImportFile
{
throw_if(
$this->importedFile === null,
\UnexpectedValueException::class,
'importedFile should not be null'
);
return $this->importedFile;
}
/** @return array<string,mixed> */
public function rules(): array
{
return [
'import' => [
'required',
'file',
'mimes:csv,txt',
'mimetypes:text/csv,text/plain,application/csv,text/comma-separated-values,text/anytext,application/octet-stream,application/txt',
'max:5120',
function ($attribute, $__, $fail): void {
$uploadedFile = $this->file('import');
$content = $uploadedFile->get();
if (
$content === false
|| $uploadedFile->getSize() === 0
|| ($uploadedFile->getMimeType() !== 'text/plain'
&& $uploadedFile->getClientMimeType() !== 'text/csv'
&& $uploadedFile->getClientMimeType() !== 'application/vnd.ms-excel')
) {
$fail(trans('validation.mimes', [
'attribute' => $attribute,
'mimes' => 'text/csv, application/vnd.ms-excel',
]));
return;
}
try {
StringEncoder::detectAndConvertToUtf8($content, 'Windows-1252');
} catch (\ValueError) {
$fail(trans('validation.encoding', [
'attribute' => $attribute,
'encoding' => 'ISO-8859-1(5), Windows-1252, UTF-8',
]));
}
},
],
];
}
#[\Override]
protected function passedValidation()
{
try {
$uploadedFile = $this->file('import');
if ($uploadedFile instanceof UploadedFile) {
$content = $uploadedFile->get();
if ($content === false) {
throw new \UnexpectedValueException('Cannot read file');
}
$utf8Content = StringEncoder::detectAndConvertToUtf8($content, 'Windows-1252');
$this->importedFile = new CsvImportFile(
$uploadedFile->getRealPath(),
$utf8Content
);
}
} catch (\Throwable) {
$this->importedFile = null;
}
}
}