Skip to content

Commit

Permalink
Throw exception when mappings are incorrect
Browse files Browse the repository at this point in the history
  • Loading branch information
emohamed committed Sep 15, 2017
1 parent 3b9baa9 commit 6fe33c3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/CsvFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,18 @@ public function set_column_names($mapping) {
$this->column_names = $mapping;
} else {
$mapping_indecies = array_flip($this->column_names);

// User code wants to map part of the columns
if (count($mapping_indecies) !== count($mapping)) {
$mapping_indecies = array_intersect_key($mapping_indecies, $mapping);
}

// some of the columns that the user code wants to map are not found
if (count($mapping_indecies) !== count($mapping)) {
$bad_cols = array_diff_key($mapping, $mapping_indecies);
throw new Exception("The following column(s) are not present in the source file: " . implode(', ', $bad_cols));
}

$this->column_names = array_combine(
$mapping_indecies,
$mapping
Expand Down
12 changes: 11 additions & 1 deletion tests/CsvFileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,17 @@ function test_non_utf8_encoded_file() {
], $csv->to_array() );
}


function test_missing_column_causes_exception() {
$this->expectException(Exception::class);

$csv = new CsvFile(__DIR__ . '/sample-data/info.csv');
$csv->use_first_row_as_header();
$csv->set_column_names([
'Last Name Typo' => 'lname',
'Address' => 'address',
]);
}

function test_map_partial_columns() {
$csv = new CsvFile(__DIR__ . '/sample-data/info.csv');
$csv->use_first_row_as_header();
Expand Down

0 comments on commit 6fe33c3

Please sign in to comment.