ldc-cocotte/app/Http/Requests/Bo/Employees/ImportRequest.php
Jérémy Munsch 2ae317aad6
refactor(employees): migrate Bo EmployeesController to CQS pattern
- Add ImportEmployees Action and ImportEmployeesInput
- Add GetEmployeeImportColumnsQuery
- Encapsulate toImportEmployeesInput in ImportRequest
- Use Executor in Bo\EmployeesController
- Add feature tests for Bo\EmployeesController
2026-10-27 09:58:42 +01:00

111 lines
3.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Requests\Bo\Employees;
use App\Actions\Employees\ImportEmployeesInput;
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;
}
public function toImportEmployeesInput(): ImportEmployeesInput
{
return new ImportEmployeesInput(
file: $this->getSalarieImportFile(),
);
}
/** @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;
}
}
}