Skip to content

Commit

Permalink
Allow partial column mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
emohamed committed Sep 15, 2017
1 parent 57b5f2b commit e330090
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/CsvFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,20 @@ private function remove_columns($old_row) {
return $new_row;
}

function convert_to_default_encoding($val) {
private function convert_to_default_encoding($val) {
return mb_convert_encoding($val, static::DEFAULT_ENCODING, $this->encoding);
}

private function format_row($row) {
if ($this->encoding !== static::DEFAULT_ENCODING) {
$row = array_map([$this, 'convert_to_default_encoding'], $row);
}
$cols = $this->get_column_names($row);
if (count($cols) !== count($row)) {
$row = array_intersect_key($row, $cols);
}
$row = array_combine(
$this->get_column_names($row),
$cols,
$row
);

Expand Down Expand Up @@ -136,8 +140,12 @@ public function set_column_names($mapping) {
if (empty($this->column_names)) {
$this->column_names = $mapping;
} else {
$mapping_indecies = array_flip($this->column_names);
if (count($mapping_indecies) !== count($mapping)) {
$mapping_indecies = array_intersect_key($mapping_indecies, $mapping);
}
$this->column_names = array_combine(
array_flip($this->column_names),
$mapping_indecies,
$mapping
);
}
Expand Down
26 changes: 26 additions & 0 deletions tests/CsvFileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -243,4 +243,30 @@ function test_non_utf8_encoded_file() {
}


function test_map_partial_columns() {
$csv = new CsvFile(__DIR__ . '/../sample-data/info.csv');
$csv->use_first_row_as_header();
$csv->set_column_names([
'Last Name' => 'lname',
'Address' => 'address',
]);
$this->assertEquals( [
[
'lname' => 'Doe',
'address' => 'Some Address 2, 12345, Country A',
],
[
'lname' => 'Dove',
'address' => 'That Address 3, 456, Country B',
],
[
'lname' => 'Smith',
'address' => '',
],
[
'lname' => 'Smith',
'address' => 'This Address 4, City, Country C',
],
], $csv->to_array() );
}
}

0 comments on commit e330090

Please sign in to comment.