feat(EmployeeCsvReaderService): refactor CSV reader creation

Updated the importEmployeesFromCsv method to use a dedicated createCsvReader method for better encoding handling and improved readability.
This commit is contained in:
Jérémy Munsch 2026-11-17 09:46:05 +01:00
parent 1085a2d4db
commit 101d0ff018
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
2 changed files with 138 additions and 1 deletions

View file

@ -35,8 +35,8 @@ class EmployeeCsvReaderService
try {
$sourceEncoding = $this->detectEncoding($fromStream);
$csv = $this->createCsvReader($fromStream);
$csv = Reader::from($fromStream);
$csv->setHeaderOffset(0);
$csv->setEscape(self::CSV_ESCAPE);
$csv->setDelimiter(self::CSV_DELIMITER);
@ -87,6 +87,34 @@ class EmployeeCsvReaderService
}
}
/**
* League\Csv stream filters (used by CharsetConverter) require a PHP stream resource
* rather than an SplFileObject instance.
*
* @return \League\Csv\Reader<array<array-key, mixed>>
*/
private function createCsvReader(\SplFileObject $fromStream): Reader
{
$realPath = $fromStream->getRealPath();
if ($realPath !== false && is_file($realPath)) {
return Reader::fromPath($realPath);
}
$fromStream->rewind();
$content = '';
while (! $fromStream->eof()) {
$chunk = $fromStream->fread(8192);
if ($chunk === false) {
throw new \UnexpectedValueException('Failed to read from input stream.');
}
$content .= $chunk;
}
$fromStream->rewind();
return Reader::fromString($content);
}
private function detectEncoding(\SplFileObject $fromStream): ?string
{
$fromStream->rewind();

View file

@ -98,4 +98,113 @@ describe('EmployeeCsvReaderService', function (): void {
expect(fn () => $service->importEmployeesFromCsv($unreadable))
->toThrow(\InvalidArgumentException::class, 'Input stream must be readable.');
});
it('imports employees from a Windows-1252 encoded CSV file', function (): void {
// GIVEN
/** @var \Psr\Log\LoggerInterface&\Mockery\MockInterface $logger */
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('debug')->once();
$logger->shouldReceive('info')->once();
$logger->shouldReceive('error')->never();
$service = new EmployeeCsvReaderService($logger);
$filePath = tempnam(sys_get_temp_dir(), 'employees-csv-win1252-');
expect($filePath)->not->toBeFalse();
$utf8Csv = implode("\n", [
'Matricule;Nom;Prénom;Date début;Date fin;Date fin prévue;Etablissement;Site;Service',
'1234567;François;Éric;01/10/2026;;;ETAB01;PA;LDCCAV030',
]);
$win1252Csv = mb_convert_encoding($utf8Csv, 'Windows-1252', 'UTF-8');
file_put_contents($filePath, $win1252Csv);
$fileObject = new \SplFileObject($filePath, 'r');
// WHEN
$items = $service->importEmployeesFromCsv($fileObject);
// THEN
$firstItem = $items[0];
assert($firstItem instanceof EmployeeCsvImportLineService);
expect($items)->toHaveCount(1)
->and($firstItem->matricule)->toBe('1234567')
->and($firstItem->lastName)->toBe('François')
->and($firstItem->firstName)->toBe('Éric')
->and($firstItem->service)->toBe('030');
unlink($filePath);
});
it('imports employees from a UTF-8 BOM CSV file', function (): void {
// GIVEN
/** @var \Psr\Log\LoggerInterface&\Mockery\MockInterface $logger */
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('debug')->once();
$logger->shouldReceive('error')->never();
$service = new EmployeeCsvReaderService($logger);
$filePath = tempnam(sys_get_temp_dir(), 'employees-csv-bom-');
expect($filePath)->not->toBeFalse();
$csvWithBom = "\xEF\xBB\xBF" . implode("\n", [
'Matricule;Nom;Prénom;Date début;Date fin;Date fin prévue;Etablissement;Site;Service',
'1234567;Dupont;Hélène;01/10/2026;;;ETAB01;PA;LDCCAV030',
]);
file_put_contents($filePath, $csvWithBom);
$fileObject = new \SplFileObject($filePath, 'r');
// WHEN
$items = $service->importEmployeesFromCsv($fileObject);
// THEN
$firstItem = $items[0];
assert($firstItem instanceof EmployeeCsvImportLineService);
expect($items)->toHaveCount(1)
->and($firstItem->firstName)->toBe('Hélène');
unlink($filePath);
});
it('imports employees from a Windows-1252 encoded SplTempFileObject', function (): void {
// GIVEN
/** @var \Psr\Log\LoggerInterface&\Mockery\MockInterface $logger */
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('debug')->once();
$logger->shouldReceive('info')->once();
$logger->shouldReceive('error')->never();
$service = new EmployeeCsvReaderService($logger);
$utf8Csv = implode("\n", [
'Matricule;Nom;Prénom;Date début;Date fin;Date fin prévue;Etablissement;Site;Service',
'1234567;Noël;Céline;01/10/2026;;;ETAB01;PA;LDCCAV030',
]);
$win1252Csv = mb_convert_encoding($utf8Csv, 'Windows-1252', 'UTF-8');
$tempFile = new class () extends \SplTempFileObject
{
public function isReadable(): bool
{
return true;
}
};
$tempFile->fwrite($win1252Csv);
$tempFile->rewind();
// WHEN
$items = $service->importEmployeesFromCsv($tempFile);
// THEN
$firstItem = $items[0];
assert($firstItem instanceof EmployeeCsvImportLineService);
expect($items)->toHaveCount(1)
->and($firstItem->lastName)->toBe('Noël')
->and($firstItem->firstName)->toBe('Céline');
});
});