From 20c1d842ac3bbcdd22d7ab2f53ce6949ef96fe5a Mon Sep 17 00:00:00 2001 From: Chris Morrell Date: Fri, 2 Aug 2024 10:18:30 -0400 Subject: [PATCH] Allow for missing headers --- .idea/blade.xml | 2 ++ src/Reader.php | 6 ++++-- tests/Feature/CsvReaderTest.php | 12 ++++++++++++ tests/fixtures/more-columns-than-headers.csv | 3 +++ 4 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 tests/fixtures/more-columns-than-headers.csv diff --git a/.idea/blade.xml b/.idea/blade.xml index fca757d..c26d63d 100644 --- a/.idea/blade.xml +++ b/.idea/blade.xml @@ -77,6 +77,7 @@ + @@ -103,6 +104,7 @@ + diff --git a/src/Reader.php b/src/Reader.php index 0e4abfd..dac580d 100644 --- a/src/Reader.php +++ b/src/Reader.php @@ -58,8 +58,10 @@ public function collect(): LazyCollection $data_columns = count($data); if ($columns < $data_columns) { - // TODO: Offer option to trim - throw new UnexpectedValueException("Expected {$columns} columns of data but got {$data_columns}"); + foreach (range(1, $data_columns) as $index => $column) { + $keys[$index] ??= "column{$column}"; + } + $columns = count($keys); } if ($columns > $data_columns) { diff --git a/tests/Feature/CsvReaderTest.php b/tests/Feature/CsvReaderTest.php index ffee221..ed2516d 100644 --- a/tests/Feature/CsvReaderTest.php +++ b/tests/Feature/CsvReaderTest.php @@ -30,4 +30,16 @@ public function test_it_can_read_a_basic_csv_file_as_a_collection(): void }, $row->toArray()); } } + + public function test_if_headers_are_missing_column_numbers_are_used_as_keys(): void + { + $collection = CsvReader::from($this->fixture('more-columns-than-headers.csv'))->collect(); + + foreach ($collection as $index => $row) { + $this->assertSame(match ($index) { + 0 => ['user_id' => 1, 'name' => 'Chris', 'column3' => null, 'column4' => 40.2, 'column5' => null, 'column6' => null, 'column7' => null], + 1 => ['user_id' => 10, 'name' => 'Bogdan', 'column3' => 'not null', 'column4' => -37, 'column5' => null, 'column6' => null, 'column7' => null], + }, $row->toArray()); + } + } } diff --git a/tests/fixtures/more-columns-than-headers.csv b/tests/fixtures/more-columns-than-headers.csv new file mode 100644 index 0000000..2d15d6d --- /dev/null +++ b/tests/fixtures/more-columns-than-headers.csv @@ -0,0 +1,3 @@ +User ID,Name +1,Chris,,40.2,,, +10,Bogdan,"not null",-37