- Replaced resource handling with SplFileObject for better readability. - Introduced ImportEmployeesOutput class for structured results. - Updated related services and tests to accommodate new structures.
193 lines
5.7 KiB
PHP
193 lines
5.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Lib;
|
|
|
|
use Fusonic\CsvReader\CsvReader;
|
|
use Fusonic\CsvReader\CsvReaderOptions;
|
|
use Fusonic\CsvReader\Exceptions\CsvReaderException;
|
|
use Fusonic\CsvReader\Mapping\MappingBuilder;
|
|
use Webmozart\Assert\Assert;
|
|
|
|
class EnhancedCsvReader extends CsvReader
|
|
{
|
|
public function __construct(
|
|
protected mixed $fileToRead,
|
|
private CsvReaderOptions $options = new CsvReaderOptions(),
|
|
private ?string $sourceEncoding = null,
|
|
) {
|
|
if (! \is_string($fileToRead) && ! ($fileToRead instanceof \SplFileObject)) {
|
|
throw new \TypeError(
|
|
sprintf(
|
|
'%s::__construct(): Argument #1 ($fileToRead) must be of type string or SplFileObject, %s given.',
|
|
self::class,
|
|
get_debug_type($fileToRead)
|
|
)
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Iterates data from the configured CSV file and maps each row to an object of type $className.
|
|
*
|
|
* @template T of object
|
|
* @template E
|
|
*
|
|
* @param class-string<T> $className the class which data should be mapped to
|
|
* @param ?callable(int, \Throwable): E $callback the callback to handle errors for each row
|
|
* @return \Traversable<int, T|E>
|
|
*/
|
|
#[\Override]
|
|
public function readObjects(string $className, ?callable $callback = null): iterable
|
|
{
|
|
$resource = $this->getResource();
|
|
|
|
/** @var int $resourcePosition */
|
|
$resourcePosition = $resource->ftell();
|
|
|
|
// Skip the BOM
|
|
if ($this->options->removeBOM) {
|
|
$this->inheritedSkipBom($resource);
|
|
}
|
|
|
|
// Read header
|
|
$header = null;
|
|
|
|
if ($this->options->hasHeaderRow) {
|
|
$header = $resource->fgetcsv(
|
|
separator: $this->options->delimiter,
|
|
enclosure: $this->options->enclosure,
|
|
escape: $this->options->escape
|
|
);
|
|
|
|
if ($header === false || $header === [null]) {
|
|
throw new CsvReaderException('Cannot get line from file pointer and parse it for CSV fields.');
|
|
}
|
|
|
|
Assert::allString($header);
|
|
$header = $this->convertRowEncoding($header);
|
|
}
|
|
|
|
// Build mapping
|
|
$mappingBuilder = new MappingBuilder();
|
|
$mapping = $mappingBuilder->build($header, $className);
|
|
|
|
$line = $this->options->hasHeaderRow ? 2 : 1;
|
|
|
|
while (! $resource->eof()) {
|
|
$row = $resource->fgetcsv(
|
|
separator: $this->options->delimiter,
|
|
enclosure: $this->options->enclosure,
|
|
escape: $this->options->escape
|
|
);
|
|
|
|
if ($row === false || $row === [null]) {
|
|
$line++;
|
|
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
Assert::allString($row);
|
|
$row = $this->convertRowEncoding($row);
|
|
|
|
yield $this->inheritedMap($row, $className, $mapping);
|
|
} catch (\Throwable $e) {
|
|
if ($callback !== null) {
|
|
yield $callback($line, $e);
|
|
} else {
|
|
throw $e;
|
|
}
|
|
}
|
|
$line++;
|
|
}
|
|
|
|
// Rewind resource to its original position or close it if source was a path
|
|
if ($this->fileToRead instanceof \SplFileObject) {
|
|
$this->fileToRead->fseek($resourcePosition);
|
|
} else {
|
|
$resource = null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param array<string> $row
|
|
* @return array<string>
|
|
*/
|
|
private function convertRowEncoding(array $row): array
|
|
{
|
|
if ($this->sourceEncoding === null || $this->sourceEncoding === 'UTF-8') {
|
|
return $row;
|
|
}
|
|
|
|
return array_map(
|
|
fn (string $value): string => mb_convert_encoding(
|
|
$value,
|
|
'UTF-8',
|
|
$this->sourceEncoding
|
|
) ?: $value,
|
|
$row
|
|
);
|
|
}
|
|
|
|
private function getResource(): \SplFileObject
|
|
{
|
|
if ($this->fileToRead instanceof \SplFileObject) {
|
|
return $this->fileToRead;
|
|
}
|
|
|
|
if (\is_string($this->fileToRead)) {
|
|
$resource = new \SplFileObject($this->fileToRead, 'r');
|
|
if (! $resource->isReadable()) {
|
|
throw new CsvReaderException('Cannot open the CSV file.');
|
|
}
|
|
|
|
return $resource;
|
|
}
|
|
|
|
throw new CsvReaderException('Invalid file to read.');
|
|
}
|
|
|
|
private function inheritedSkipBom(\SplFileObject $resource): void
|
|
{
|
|
$position = $resource->ftell();
|
|
|
|
if ($position === false) {
|
|
throw new CsvReaderException('Cannot read the current position of the file read/write pointer.');
|
|
}
|
|
|
|
if ($resource->fread(3) !== \chr(0xEF) . \chr(0xBB) . \chr(0xBF)) {
|
|
$resource->fseek($position);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @template T of object
|
|
*
|
|
* @param array<string> $row
|
|
* @param class-string<T> $className
|
|
* @param \Fusonic\CsvReader\Mapping\MappingInfo[] $mappings
|
|
* @return T
|
|
*/
|
|
protected function inheritedMap(array $row, string $className, array $mappings): object
|
|
{
|
|
$object = new $className();
|
|
|
|
foreach ($mappings as $mapping) {
|
|
if (! array_key_exists($mapping->getIndex(), $row)) {
|
|
throw new CsvReaderException("Column index {$mapping->getIndex()} does not exist in CSV row.");
|
|
}
|
|
|
|
$mapping->setValue(
|
|
$object,
|
|
$this->options->valueConverter->convert(
|
|
$row[$mapping->getIndex()],
|
|
$mapping->getType()
|
|
)
|
|
);
|
|
}
|
|
|
|
return $object;
|
|
}
|
|
}
|