Skip to content

Commit f42b83f

Browse files
authoredSep 18, 2023
throw error if column is not available (#23)
Signed-off-by: rahul <[email protected]>
1 parent 8049fa9 commit f42b83f

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed
 

‎src/CsvFileHandler.php

+4
Original file line numberDiff line numberDiff line change
@@ -209,9 +209,13 @@ private function replaceKeywordInRow(array &$row, string $keyword, string $repla
209209
* @param string $keyword
210210
* @param string $replace
211211
* @return int
212+
* @throws FileHandlerException
212213
*/
213214
private function replaceKeywordInColumn(array &$row, string $column, string $keyword, string $replace): int
214215
{
216+
if (!array_key_exists($column, $row)) {
217+
throw new FileHandlerException("invalid column name");
218+
}
215219
$count = 0;
216220

217221
if ($keyword === $row[$column]) {

‎tests/unit/CsvFileHandlerTest.php

+18
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,15 @@ protected function tearDown(): void
3737
$this->csvFileHandler = null;
3838
}
3939

40+
#[Test]
41+
#[DataProvider("wrongColumnNameProvider")]
42+
public function throwExceptionIfWrongColumnNameProvided(string $columnName): void
43+
{
44+
$this->expectException(FileHandlerException::class);
45+
$this->expectExceptionMessage("invalid column name");
46+
$this->csvFileHandler->findAndReplaceInCsv("movie.csv", "Twilight", "hello", $columnName);
47+
}
48+
4049

4150
#[Test]
4251
public function findAndReplaceInCsvMethodShouldReplaceTextWithoutColumnOption(): void
@@ -202,4 +211,13 @@ public static function fileProvider(): iterable
202211
yield [$file2];
203212
yield [$file3];
204213
}
214+
215+
/**
216+
* @return iterable<array<string>>
217+
*/
218+
public static function wrongColumnNameProvider(): iterable
219+
{
220+
yield ["wrong"];
221+
yield ["honey bee"];
222+
}
205223
}

0 commit comments

Comments
 (0)
Please sign in to comment.