Skip to content

Commit

Permalink
skip empty rows by default
Browse files Browse the repository at this point in the history
  • Loading branch information
lpheller committed Nov 4, 2023
1 parent 025097d commit 890f9d2
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Csv.php
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,13 @@ public function each($callback)
}
}

public function skipEmptyRows($shouldSkip = true)
{
$this->processor->skipEmptyRows = $shouldSkip;

return $this;
}

/**
* Get the CSV data as JSON.
* Warning: This will load the entire CSV into memory, so it shouldn't be
Expand Down
6 changes: 6 additions & 0 deletions src/CsvProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ class CsvProcessor

public string $delimiter = ',';

public bool $skipEmptyRows = false;

public array $headers = [];

public function __construct(public FileHandler $fileHandler)
Expand All @@ -44,6 +46,10 @@ public function process()
continue; // Skip rows based on specified row numbers
}

if ($this->skipEmptyRows && empty(array_filter($row))) {
continue; // Skip empty rows
}

$row = $this->prepareRow($row);

if ($this->filterCallback instanceof \Closure && ! call_user_func($this->filterCallback, $row)) {
Expand Down
4 changes: 4 additions & 0 deletions tests/Fixtures/data_with_empty_rows.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Foo,Bar,Baz
Foo1,Bar1,Baz1
,,
Foo3,Bar3,Baz3
13 changes: 13 additions & 0 deletions tests/Unit/CsvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -366,3 +366,16 @@ function makeTestFile($rows = 1000)

unlink($file);
});

test('it skips empty rows by default', function () {
$file = __DIR__.'/../Fixtures/data_with_empty_rows.csv';
$csv = Csv::from($file)
->mapToHeaders()
->skipEmptyRows();

expect($csv->count())->toBe(2);

$csv->skipEmptyRows(false);
expect($csv->count())->toBe(3);

});

0 comments on commit 890f9d2

Please sign in to comment.