55use Generator ;
66use Rcsofttech85 \FileHandler \Exception \FileHandlerException ;
77use Rcsofttech85 \FileHandler \Utilities \RowColumnHelper ;
8+ use Rcsofttech85 \FileHandler \Validator \FileValidatorTrait ;
89
910class CsvFileHandler
1011{
1112 use RowColumnHelper;
13+ use FileValidatorTrait;
1214
1315 public function __construct (
1416 private readonly TempFileHandler $ tempFileHandler
@@ -29,11 +31,6 @@ public function searchInCsvFile(
2931 string $ column ,
3032 string |null $ format = null
3133 ): bool |array {
32- if (!file_exists ($ filename )) {
33- throw new FileHandlerException ('file not found ' );
34- }
35-
36-
3734 foreach ($ this ->getRows ($ filename ) as $ row ) {
3835 if ($ keyword === $ row [$ column ]) {
3936 return ($ format === FileHandler::ARRAY_FORMAT ) ? $ row : true ;
@@ -42,6 +39,11 @@ public function searchInCsvFile(
4239 return false ;
4340 }
4441
42+ /**
43+ * @param string $filename
44+ * @return string|false
45+ * @throws FileHandlerException
46+ */
4547
4648 public function toJson (string $ filename ): string |false
4749 {
@@ -53,18 +55,23 @@ public function toJson(string $filename): string|false
5355 /**
5456 * @param string $filename
5557 * @param array<string> $hideColumns
58+ * @param int|false $limit
5659 * @return array<int,array<string,string>>
5760 * @throws FileHandlerException
5861 */
5962 public function toArray (string $ filename , array |false $ hideColumns = false , int |false $ limit = false ): array
6063 {
61- if (!file_exists ($ filename )) {
62- throw new FileHandlerException ('file not found ' );
63- }
64-
6564 return iterator_to_array ($ this ->getRows ($ filename , $ hideColumns , $ limit ));
6665 }
6766
67+ /**
68+ * @param string $filename
69+ * @param string $keyword
70+ * @param string $replace
71+ * @param string|null $column
72+ * @return bool
73+ * @throws FileHandlerException
74+ */
6875 public function findAndReplaceInCsv (
6976 string $ filename ,
7077 string $ keyword ,
@@ -160,6 +167,7 @@ private function isValidCsvFileFormat(array $row): bool
160167 */
161168 private function getRows (string $ filename , array |false $ hideColumns = false , int |false $ limit = false ): Generator
162169 {
170+ $ filename = $ this ->validateFileName ($ filename );
163171 $ csvFile = fopen ($ filename , 'r ' );
164172 if (!$ csvFile ) {
165173 throw new FileHandlerException ('file not found ' );
0 commit comments