diff --git a/CHANGELOG.md b/CHANGELOG.md index f1de8740..5942a593 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ Latest ------ +## Changes +* [#507](https://github.com/cleverage/process-bundle/issues/507) `csv_reader`, `input_csv_reader`: a line that cannot be read (number of columns not matching the headers, line that cannot be parsed) sends `['csv_file' => , 'csv_line' => , 'csv_values' => ]` to the error output, instead of the input of the task (`null`, or the file path for `input_csv_reader`, see `UPGRADE.md`), and `csv_file` / `csv_line` are in the error context of the logged error. `CsvResource::readLine()` throws an `InvalidCsvLineException` (an `UnexpectedValueException`) carrying the values read. Update documentation, add tests. + v5.10 ----- diff --git a/UPGRADE.md b/UPGRADE.md index c7215174..a27572f7 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -1,6 +1,14 @@ Upgrade Guide ============= +## v6.0 + +### Error output of the CSV readers + +A line that `csv_reader` or `input_csv_reader` cannot read (number of columns not matching the headers, line that +cannot be parsed) sends `['csv_file' => , 'csv_line' => , 'csv_values' => ]` to the +error output. Before, `input_csv_reader` sent its input, the file path: read it from `[csv_file]` in the error branch. + ## v5.10 ### Stop strategy and error branch ending on a stop diff --git a/docs/reference/tasks/csv_reader_task.md b/docs/reference/tasks/csv_reader_task.md index 699628f2..e106da47 100644 --- a/docs/reference/tasks/csv_reader_task.md +++ b/docs/reference/tasks/csv_reader_task.md @@ -25,6 +25,18 @@ Underlying method is [fgetcsv](https://www.php.net/manual/en/function.fgetcsv.ph When no line can be read (typically the trailing empty line at the end of the file), no output is produced and the task is skipped for this iteration. +When a line cannot be read (its number of columns does not match the headers, or it cannot be parsed), an +`InvalidCsvLineException` is thrown, handled according to the task `error_strategy`, and the error output is the +invalid line instead of the input of the task: + +```php +[ + 'csv_file' => '/path/to/file.csv', // path of the file + 'csv_line' => 7, // physical line number, the header being line 1 + 'csv_values' => ['Dracula', 'Bram'], // values read by fgetcsv(), null when the line cannot be parsed +] +``` + Options ------- @@ -67,13 +79,32 @@ entry: outputs: [transform] ``` +* Reject the invalid lines to a CSV file and go on with the following lines + +```yaml +# Task configuration level +read: + task: csv_reader + options: + file_path: '%kernel.project_dir%/var/data/catalog.csv' + outputs: [import] + error_strategy: skip + error_outputs: [write_rejects] +write_rejects: + task: csv_writer # csv_file;csv_line;csv_values, the values joined by "|" + options: + file_path: '%kernel.project_dir%/var/data/catalog_rejects.csv' +``` + Notes ----- -* Each line must contain exactly as many columns as there are headers, otherwise an `UnexpectedValueException` is thrown. +* Each line must contain exactly as many columns as there are headers, otherwise an `InvalidCsvLineException` (an + `UnexpectedValueException`) is thrown and the line is sent to the error output (see [Possible outputs](#possible-outputs)). * A UTF-8 BOM is removed from the first header when headers are read from the file. If the first line is blank, an `UnexpectedValueException` is thrown. -* `csv_file` and `csv_line` are added to the error context of the process. +* `csv_file` and `csv_line` (the line being read) are added to the error context of the process, also when the line + cannot be read. * The file is closed once fully read: if the task is executed again (e.g. for a new input), the file is read again from its beginning. * See also [InputCsvReaderTask](input_csv_reader_task.md) to read a file path given as input. diff --git a/docs/reference/tasks/input_csv_reader_task.md b/docs/reference/tasks/input_csv_reader_task.md index 6902d6f1..cf11f66b 100644 --- a/docs/reference/tasks/input_csv_reader_task.md +++ b/docs/reference/tasks/input_csv_reader_task.md @@ -28,6 +28,18 @@ Underlying method is [fgetcsv](https://www.php.net/manual/en/function.fgetcsv.ph When no line can be read (typically the trailing empty line at the end of the file), no output is produced and the task is skipped for this iteration. +When a line cannot be read (its number of columns does not match the headers, or it cannot be parsed), an +`InvalidCsvLineException` is thrown, handled according to the task `error_strategy`, and the error output is the +invalid line instead of the input of the task (the file path, given as `csv_file`; it was the error output before v6.0): + +```php +[ + 'csv_file' => '/path/to/file.csv', // path of the file + 'csv_line' => 7, // physical line number, the header being line 1 + 'csv_values' => ['Dracula', 'Bram'], // values read by fgetcsv(), null when the line cannot be parsed +] +``` + Options ------- diff --git a/src/Exception/InvalidCsvLineException.php b/src/Exception/InvalidCsvLineException.php new file mode 100644 index 00000000..fe0d99b0 --- /dev/null +++ b/src/Exception/InvalidCsvLineException.php @@ -0,0 +1,39 @@ +|null $values the values read by fgetcsv(), null when the line cannot be parsed + */ + public function __construct( + string $message, + private readonly ?array $values = null, + ) { + parent::__construct($message); + } + + /** + * @return list|null the values read by fgetcsv(), null when the line cannot be parsed + */ + public function getValues(): ?array + { + return $this->values; + } +} diff --git a/src/Filesystem/CsvResource.php b/src/Filesystem/CsvResource.php index b945ee49..2df01927 100644 --- a/src/Filesystem/CsvResource.php +++ b/src/Filesystem/CsvResource.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Filesystem; +use CleverAge\ProcessBundle\Exception\InvalidCsvLineException; use CleverAge\ProcessBundle\Exception\LogicException; use CleverAge\ProcessBundle\Exception\RuntimeException; use CleverAge\ProcessBundle\Exception\UnexpectedValueException; @@ -176,6 +177,8 @@ public function readRaw(?int $length = null): array|false * @param int<0, max>|null $length * * @return array|null + * + * @throws InvalidCsvLineException when the line cannot be parsed or its number of columns does not match the headers */ public function readLine(?int $length = null): ?array { @@ -187,14 +190,14 @@ public function readLine(?int $length = null): ?array return null; } $message = "Unable to parse data {$filePosition} for {$this->getResourceName()}"; - throw new UnexpectedValueException($message); + throw new InvalidCsvLineException($message); } $count = \count($values); if ($count !== $this->headerCount) { $message = "Number of columns not matching {$filePosition} for {$this->getResourceName()}: "; $message .= "{$count} columns for {$this->headerCount} headers"; - throw new UnexpectedValueException($message); + throw new InvalidCsvLineException($message, $values); } try { diff --git a/src/Task/File/Csv/CsvReaderTask.php b/src/Task/File/Csv/CsvReaderTask.php index 0736dcce..30bbe352 100644 --- a/src/Task/File/Csv/CsvReaderTask.php +++ b/src/Task/File/Csv/CsvReaderTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\File\Csv; +use CleverAge\ProcessBundle\Exception\InvalidCsvLineException; use CleverAge\ProcessBundle\Exception\LogicException; use CleverAge\ProcessBundle\Filesystem\CsvFile; use CleverAge\ProcessBundle\Model\IterableTaskInterface; @@ -47,7 +48,20 @@ public function execute(ProcessState $state): void throw new LogicException('No CSV File initialized'); } $lineNumber = $csv->getLineNumber(); - $output = $csv->readLine(); + $state->addErrorContextValue('csv_file', $csv->getFilePath()); + $state->addErrorContextValue('csv_line', $lineNumber); + try { + $output = $csv->readLine(); + } catch (InvalidCsvLineException $e) { + // The error branch gets the invalid line instead of the input of the task + $state->setErrorOutput([ + 'csv_file' => $csv->getFilePath(), + 'csv_line' => $lineNumber, + 'csv_values' => $e->getValues(), + ]); + + throw $e; + } if (null === $output) { if ($this->getOption($state, 'log_empty_lines')) { @@ -61,8 +75,6 @@ public function execute(ProcessState $state): void $state->setSkipped(true); } - $state->addErrorContextValue('csv_file', $csv->getFilePath()); - $state->addErrorContextValue('csv_line', $lineNumber); $state->setOutput($output); } diff --git a/tests/Filesystem/CsvResourceTest.php b/tests/Filesystem/CsvResourceTest.php index 11cd46e3..76cdfcbc 100644 --- a/tests/Filesystem/CsvResourceTest.php +++ b/tests/Filesystem/CsvResourceTest.php @@ -13,10 +13,12 @@ namespace CleverAge\ProcessBundle\Tests\Filesystem; +use CleverAge\ProcessBundle\Exception\InvalidCsvLineException; use CleverAge\ProcessBundle\Filesystem\CsvResource; use PHPUnit\Framework\TestCase; #[\PHPUnit\Framework\Attributes\CoversClass(CsvResource::class)] +#[\PHPUnit\Framework\Attributes\CoversClass(InvalidCsvLineException::class)] class CsvResourceTest extends TestCase { public function testHeadersAreReadFromTheFirstLine(): void @@ -35,6 +37,19 @@ public function testBlankFirstLineIsRejected(): void new CsvResource($this->createResource("\na;b\n"), ';'); } + public function testLineWithAnotherNumberOfColumnsThrowsWithItsValues(): void + { + $csv = new CsvResource($this->createResource("a;b\n1;2;3\n"), ';'); + + try { + $csv->readLine(); + self::fail('An InvalidCsvLineException should have been thrown'); + } catch (InvalidCsvLineException $e) { + self::assertStringStartsWith('Number of columns not matching on line 2 for ', $e->getMessage()); + self::assertSame(['1', '2', '3'], $e->getValues()); + } + } + public function testTellReturnsThePositionInTheResource(): void { $csv = new CsvResource($this->createResource("a;b\n1;2\n"), ';'); diff --git a/tests/Task/File/Csv/CsvReaderTaskTest.php b/tests/Task/File/Csv/CsvReaderTaskTest.php index dd448bc4..d2b457c3 100644 --- a/tests/Task/File/Csv/CsvReaderTaskTest.php +++ b/tests/Task/File/Csv/CsvReaderTaskTest.php @@ -16,6 +16,7 @@ use CleverAge\ProcessBundle\Configuration\ProcessConfiguration; use CleverAge\ProcessBundle\Configuration\TaskConfiguration; use CleverAge\ProcessBundle\Context\ContextualOptionResolver; +use CleverAge\ProcessBundle\Exception\InvalidCsvLineException; use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Filesystem\CsvFile; use CleverAge\ProcessBundle\Filesystem\CsvResource; @@ -33,6 +34,7 @@ #[\PHPUnit\Framework\Attributes\CoversClass(CsvReaderTask::class)] #[\PHPUnit\Framework\Attributes\CoversClass(InputCsvReaderTask::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(InvalidCsvLineException::class)] #[\PHPUnit\Framework\Attributes\UsesClass(UnexpectedValueException::class)] #[\PHPUnit\Framework\Attributes\UsesClass(AbstractCsvTask::class)] #[\PHPUnit\Framework\Attributes\UsesClass(AbstractCsvResourceTask::class)] @@ -132,6 +134,64 @@ public function testInputCsvReaderBasePathMustBeAString(): void $this->iterate(new InputCsvReaderTask(new NullLogger()), $this->createState(['base_path' => ['a']]), 'b.csv'); } + /** + * A line that cannot be read sends its file, physical line number and values to the error branch, and they are in + * the error context of the logged error; the following lines are still read. + */ + public function testInvalidLineErrorOutputHasItsLineNumberAndValues(): void + { + $path = $this->tmpDir.'/invalid.csv'; + (new Filesystem())->dumpFile($path, "id;name\n1;foo\n2\n3;bar;extra\n4;baz\n"); + $expectedErrors = [ + ['csv_file' => $path, 'csv_line' => 3, 'csv_values' => ['2']], + ['csv_file' => $path, 'csv_line' => 4, 'csv_values' => ['3', 'bar', 'extra']], + ]; + $expectedOutputs = [['id' => '1', 'name' => 'foo'], ['id' => '4', 'name' => 'baz']]; + + $task = new CsvReaderTask(new NullLogger()); + $state = $this->createState(['file_path' => $path]); + self::assertSame([$expectedOutputs, $expectedErrors], $this->iterateWithErrors($task, $state)); + $task->finalize($state); + + $task = new InputCsvReaderTask(new NullLogger()); + $state = $this->createState([]); + self::assertSame([$expectedOutputs, $expectedErrors], $this->iterateWithErrors($task, $state, $path)); + $task->finalize($state); + } + + /** + * Mimics the ProcessManager loop over an iterable task with the skip error strategy: returns the outputs and the + * error outputs, checking that the error context matches the error output. + * + * @return array{list, list} + */ + private function iterateWithErrors(CsvReaderTask $task, ProcessState $state, mixed $input = null): array + { + $outputs = []; + $errors = []; + do { + $state->reset(true); + $state->setInput($input); + try { + $task->execute($state); + if (!$state->isSkipped()) { + $outputs[] = $state->getOutput(); + } + } catch (InvalidCsvLineException) { + self::assertTrue($state->hasErrorOutput()); + $errorOutput = $state->getErrorOutput(); + self::assertIsArray($errorOutput); + self::assertSame( + ['csv_file' => $errorOutput['csv_file'], 'csv_line' => $errorOutput['csv_line']], + $state->getErrorContext(), + ); + $errors[] = $errorOutput; + } + } while ($task->next($state)); + + return [$outputs, $errors]; + } + /** * Mimics the ProcessManager loop over an iterable task and returns the non-skipped outputs. *