diff --git a/src/CsvFileHandler.php b/src/CsvFileHandler.php index 298a09e..ce308d1 100644 --- a/src/CsvFileHandler.php +++ b/src/CsvFileHandler.php @@ -209,9 +209,13 @@ private function replaceKeywordInRow(array &$row, string $keyword, string $repla * @param string $keyword * @param string $replace * @return int + * @throws FileHandlerException */ private function replaceKeywordInColumn(array &$row, string $column, string $keyword, string $replace): int { + if (!array_key_exists($column, $row)) { + throw new FileHandlerException("invalid column name"); + } $count = 0; if ($keyword === $row[$column]) { diff --git a/tests/unit/CsvFileHandlerTest.php b/tests/unit/CsvFileHandlerTest.php index 2ae92f9..edb5b18 100644 --- a/tests/unit/CsvFileHandlerTest.php +++ b/tests/unit/CsvFileHandlerTest.php @@ -37,6 +37,15 @@ protected function tearDown(): void $this->csvFileHandler = null; } + #[Test] + #[DataProvider("wrongColumnNameProvider")] + public function throwExceptionIfWrongColumnNameProvided(string $columnName): void + { + $this->expectException(FileHandlerException::class); + $this->expectExceptionMessage("invalid column name"); + $this->csvFileHandler->findAndReplaceInCsv("movie.csv", "Twilight", "hello", $columnName); + } + #[Test] public function findAndReplaceInCsvMethodShouldReplaceTextWithoutColumnOption(): void @@ -202,4 +211,13 @@ public static function fileProvider(): iterable yield [$file2]; yield [$file3]; } + + /** + * @return iterable> + */ + public static function wrongColumnNameProvider(): iterable + { + yield ["wrong"]; + yield ["honey bee"]; + } }