38 lines
1.4 KiB
PHP
38 lines
1.4 KiB
PHP
<?php
|
|
namespace Sudalys\ImportService;
|
|
|
|
use Sudalys\ImportService\Interfaces\HeaderSpecificationInterface;
|
|
use Sudalys\ImportService\Result\ValidationResult;
|
|
use Sudalys\ImportService\Interfaces\ValidatorInterface;
|
|
|
|
class CsvValidator implements ValidatorInterface
|
|
{
|
|
public function __construct(private HeaderSpecificationInterface $headerSpecification, private $columnSpecification){}
|
|
public function validate(array $header, iterable $records): ValidationResult
|
|
{
|
|
$errors = [];
|
|
$validData = [];
|
|
|
|
if (!$this->headerSpecification->isSatisfiedBy($header)) {
|
|
$errors[] = $this->headerSpecification->getErrorMessage();
|
|
$errors = array_merge($errors, $this->headerSpecification->getErrorsHeader($header));
|
|
}
|
|
$rowIndex = 2;
|
|
foreach ($records as $row){
|
|
$rowErrors = [];
|
|
foreach ($this->columnSpecification as $column => $specification) {
|
|
if (!isset($row[$column]) || !$specification->isSatisfiedBy($row[$column])) {
|
|
$rowErrors[] = "Ligne $rowIndex: " . $specification->getErrorMessage();
|
|
}
|
|
}
|
|
if (!empty($rowErrors)) {
|
|
$errors = array_merge($errors, $rowErrors);
|
|
} else {
|
|
$validData[] = $row;
|
|
}
|
|
$rowIndex++;
|
|
}
|
|
return new ValidationResult( $errors, $validData);
|
|
}
|
|
|
|
} |