ImportService/src/Service/Import/CsvImportService.php

65 lines
2.2 KiB
PHP

<?php
namespace Sudalys\ImportService;
use Sudalys\ImportService\CsvValidator;
use Sudalys\ImportService\Processor\BasicCsvFileProcessor;
use Sudalys\ImportService\Processor\MainProcessor;
use Sudalys\ImportService\ErrorHandler\LoggingErrorHandler;
use Sudalys\ImportService\Specification\ExactHeaderSpecification;
use Sudalys\ImportService\Specification\RegexColumnSpecification;
use Sudalys\ImportService\Specification\NumericSpecification;
use Sudalys\ImportService\Specification\RequiredColumnSpecification;
use Sudalys\ImportService\Result\ImportResult;
use Psr\Log\LoggerInterface;
class CsvImportService
{
private CsvImporter $importer;
private array $header;
private array $regexListe;
public function __construct()
{}
public function import(string $filePath, array $header, array $regexListe, array $requiredColumns, LoggerInterface $logger): array
{
$this->header = $header;
$this->regexListe = $regexListe;
$headerSpec = new ExactHeaderSpecification($this->header);
$columnSpecs = [];
foreach ($header as $col) {
// Si regex définie → priorité
if (isset($regexListe[$col])) {
$columnSpecs[$col] = new RegexColumnSpecification(
$regexListe[$col],
"Le format de la colonne '$col' est invalide."
);
}
elseif (in_array($col, $requiredColumns)) {
$columnSpecs[$col] = new RequiredColumnSpecification("La colonne '$col' est obligatoire.");
}
}
$fileProcessor = new BasicCsvFileProcessor();
$validator = new CsvValidator($headerSpec, $columnSpecs);
$errorHandler = new LoggingErrorHandler($logger);
$mainProcessor = new MainProcessor();
$this->importer = new CsvImporter($fileProcessor, $validator,$errorHandler,
$mainProcessor,
);
$result = $this->importer->import($filePath);
return [
'success' => $result->isSuccess(),
'errors' => $result->getErrors(),
'processedCount' => $result->getProcessedCount(),
'message' => $result->getMessage(),
];
}
}