ldc-cocotte/app/Services/EmployeeCsvReaderService.php

125 lines
3.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
use League\Csv\CharsetConverter;
use League\Csv\Reader;
use League\Csv\Serializer\Denormalizer;
use Psr\Log\LoggerInterface;
use Webmozart\Assert\Assert;
class EmployeeCsvReaderService
{
private const string CSV_ESCAPE = '';
private const string CSV_DELIMITER = ';';
public function __construct(
private readonly LoggerInterface $logger
) {
}
/**
* @return array<int, EmployeeCsvImportLineService|string>
*/
public function importEmployeesFromCsv(\SplFileObject $fromStream): array
{
if (! $fromStream->isReadable()) {
$this->logger->error('Input stream is not readable.');
throw new \InvalidArgumentException('Input stream must be readable.');
}
$this->logger->debug('Input stream is readable.');
try {
$sourceEncoding = $this->detectEncoding($fromStream);
$csv = Reader::from($fromStream);
$csv->setHeaderOffset(0);
$csv->setEscape(self::CSV_ESCAPE);
$csv->setDelimiter(self::CSV_DELIMITER);
if ($sourceEncoding !== null) {
CharsetConverter::addTo($csv, $sourceEncoding, 'UTF-8');
}
// * Trim lines.
$csv->addFormatter(static fn (array $row): array => array_map(
static fn (mixed $value): ?string => is_string($value) ? mb_trim($value) : null,
$row
));
$results = [];
$headers = array_map(trim(...), $csv->getHeader());
$denormalizer = new Denormalizer(EmployeeCsvImportLineService::class, $headers);
foreach ($csv->getRecords() as $offset => $record) {
try {
$mappedObject = $denormalizer->denormalize($record);
Assert::isInstanceOf($mappedObject, EmployeeCsvImportLineService::class);
$results[] = $mappedObject;
} catch (\Throwable $e) {
$line = $offset + 1;
$this->logger->error('Failed to read line from CSV.', [
'line' => $line,
'exception' => $e,
]);
$results[] = $e->getMessage();
}
}
return $results;
} catch (\Throwable $e) {
$this->logger->error('Failed to read employees from CSV.', [
'exception' => $e,
]);
if (function_exists('report')) {
report($e);
}
return [];
}
}
private function detectEncoding(\SplFileObject $fromStream): ?string
{
$fromStream->rewind();
$sample = $fromStream->fread(4096);
if ($sample === false) {
$this->logger->error('Failed to read sample from input stream.');
throw new \UnexpectedValueException('Failed to read sample from input stream.');
}
// ? Has BOM UTF-8 at the beginning of the sample ?
if (str_starts_with($sample, "\xEF\xBB\xBF")) {
$fromStream->rewind();
return null;
}
$safeSample = strlen($sample) === 4096 ? mb_strcut($sample, 0, 4092, 'UTF-8') : $sample;
// * Detect encoding.
$detected = mb_detect_encoding($safeSample, ['UTF-8', 'Windows-1252', 'ISO-8859-1'], true);
// * Rewind before reading with EnhancedCsvReader.
$fromStream->rewind();
if ($detected !== false && $detected !== 'UTF-8') {
$this->logger->info('Detected non-UTF-8 encoding, applying conversion.', [
'detected' => $detected,
]);
return $detected;
}
return null;
}
}