Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Csv Extractor: throw a proper error when the fields qty doesn't match the columns one #20

Closed
ecourtial opened this issue Mar 14, 2020 · 1 comment
Assignees
Labels
good first issue Good for newcomers

Comments

@ecourtial
Copy link
Collaborator

Example of implementation (does not require doc update):

    /**
     * Extract data from the input.
     */
    public function extract(): \Generator
    {
        $handle = fopen($this->input, 'r');

        $columns = $this->makeColumns($handle);
        $rowIndex = 1;

        while ($row = fgets($handle)) {
            $rowIndex++;

            yield new Row($this->makeRow($row, $columns, $rowIndex));
        }

        fclose($handle);
    }

    /**
     * Converts the row string to array.
     */
    protected function makeRow(string $row, array $columns, int $rowIndex): array
    {
        $row = str_getcsv($row, $this->delimiter, $this->enclosure);

        $data = [];

        $rowCount = count($row);
        $columnsCount = count($columns);
        if ($rowCount !== $columnsCount) {
            throw new \LogicException("Row with index #{$rowIndex} only contains $rowCount elements while $columnsCount were expected.");
        }

        foreach ($columns as $column => $index) {
            $data[$column] = $row[$index - 1];
        }

        return $data;
    }
@ecourtial
Copy link
Collaborator Author

Done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

1 participant