Skip to content

Commit

Permalink
Allow for missing headers
Browse files Browse the repository at this point in the history
  • Loading branch information
inxilpro committed Aug 2, 2024
1 parent 6d68210 commit 20c1d84
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .idea/blade.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions src/Reader.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
12 changes: 12 additions & 0 deletions tests/Feature/CsvReaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}
}
3 changes: 3 additions & 0 deletions tests/fixtures/more-columns-than-headers.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
User ID,Name
1,Chris,,40.2,,,
10,Bogdan,"not null",-37

0 comments on commit 20c1d84

Please sign in to comment.