Skip to content

Commit

Permalink
map to custom headers
Browse files Browse the repository at this point in the history
  • Loading branch information
lpheller committed Oct 4, 2023
1 parent e93fed5 commit e2be619
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/Csv.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ class Csv

protected $delimiter = ',';

protected $headers = [];

public function __construct(string $filePath)
{
$this->filePath = $filePath;
Expand Down Expand Up @@ -64,9 +66,17 @@ public function delimiter(string $delimiter)
*/
public function mapToHeaders($row = 1)
{
$this->setHeaderRow($row);
$this->mapToHeaderRow = true;

if (is_array($row)) {
$this->skipRows([]);
$this->headers = $row;

return $this;
}

$this->setHeaderRow($row);

// Skip the header row when processing the CSV
$this->skipRows([$this->headerRow]);

Expand Down Expand Up @@ -94,6 +104,10 @@ public function setHeaderRow($row)
*/
public function getHeaderRow()
{
if ($this->headers) {
return $this->headers;
}

$handle = $this->openFile();

// Skip rows until the header row
Expand Down
28 changes: 28 additions & 0 deletions tests/Unit/CsvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -325,3 +325,31 @@ function makeTestFile($rows = 1000)

unlink($file);
});

test('It maps to custom headers', function () {

$file = makeTestFile(2);

$csv = Csv::from($file)
->mapToHeaders([
'fii',
'foo',
'faa',
])
->get();

expect($csv)->toBe([
[
'fii' => 'Foo',
'foo' => 'Bar',
'faa' => 'Baz',
],
[
'fii' => 'Foo0',
'foo' => 'Bar0',
'faa' => 'Baz0',
],
]);

unlink($file);
});

0 comments on commit e2be619

Please sign in to comment.