Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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' => <path>, 'csv_line' => <line number>, 'csv_values' => <values read>]` 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
-----

Expand Down
8 changes: 8 additions & 0 deletions UPGRADE.md
Original file line number Diff line number Diff line change
@@ -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' => <path>, 'csv_line' => <line number>, 'csv_values' => <values read>]` 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
Expand Down
35 changes: 33 additions & 2 deletions docs/reference/tasks/csv_reader_task.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
-------

Expand Down Expand Up @@ -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.
12 changes: 12 additions & 0 deletions docs/reference/tasks/input_csv_reader_task.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
-------

Expand Down
39 changes: 39 additions & 0 deletions src/Exception/InvalidCsvLineException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

/*
* This file is part of the CleverAge/ProcessBundle package.
*
* Copyright (c) Clever-Age
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace CleverAge\ProcessBundle\Exception;

/**
* Thrown when a line of a CSV file cannot be read: it cannot be parsed, or its number of columns does not match the
* headers. Carries the values read, to report the invalid line.
*/
class InvalidCsvLineException extends UnexpectedValueException
{
/**
* @param list<string|null>|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<string|null>|null the values read by fgetcsv(), null when the line cannot be parsed
*/
public function getValues(): ?array
{
return $this->values;
}
}
7 changes: 5 additions & 2 deletions src/Filesystem/CsvResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -176,6 +177,8 @@ public function readRaw(?int $length = null): array|false
* @param int<0, max>|null $length
*
* @return array<string, string|null>|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
{
Expand All @@ -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 {
Expand Down
18 changes: 15 additions & 3 deletions src/Task/File/Csv/CsvReaderTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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')) {
Expand All @@ -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);
}

Expand Down
15 changes: 15 additions & 0 deletions tests/Filesystem/CsvResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"), ';');
Expand Down
60 changes: 60 additions & 0 deletions tests/Task/File/Csv/CsvReaderTaskTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)]
Expand Down Expand Up @@ -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<mixed>, list<mixed>}
*/
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.
*
Expand Down