diff --git a/phpstan-baseline-8+.neon b/phpstan-baseline-8+.neon index 45a2f3a..e528d50 100644 --- a/phpstan-baseline-8+.neon +++ b/phpstan-baseline-8+.neon @@ -131,7 +131,7 @@ parameters: path: src/CsvWriter.php - - message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, bool\\|float\\|int\\|object\\|string given\\.$#" + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, float\\|int\\|object\\|string\\|true given\\.$#" count: 1 path: src/CsvWriter.php diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index a850342..89f517e 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -136,7 +136,7 @@ parameters: path: src/CsvWriter.php - - message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, bool\\|float\\|int\\|object\\|string given\\.$#" + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, float\\|int\\|object\\|string\\|true given\\.$#" count: 1 path: src/CsvWriter.php diff --git a/src/CsvWriter.php b/src/CsvWriter.php index 24452d4..790f15e 100644 --- a/src/CsvWriter.php +++ b/src/CsvWriter.php @@ -142,9 +142,12 @@ public function rowToStr(array $row) ); } - $return[] = $this->getEnclosure() . - str_replace($this->getEnclosure(), str_repeat($this->getEnclosure(), 2), $column ?? '') . - $this->getEnclosure(); + $enclosure = $this->getEnclosure(); + $escapedEnclosure = str_repeat($enclosure, 2); + $columnValue = ($column === false) ? '0' : ($column ?? ''); + + $escapedColumn = str_replace($enclosure, $escapedEnclosure, $columnValue); + $return[] = sprintf('%s%s%s', $enclosure, $escapedColumn, $enclosure); } return implode($this->getDelimiter(), $return) . $this->lineBreak; } diff --git a/tests/CsvWriteTest.php b/tests/CsvWriteTest.php index c35425c..d3d5507 100644 --- a/tests/CsvWriteTest.php +++ b/tests/CsvWriteTest.php @@ -53,6 +53,21 @@ public function testWrite() [ 'column with \n \t \\\\', 'second col', ], + [ + 1, true, + ], + [ + 2, false, + ], + [ + 3, null, + ], + [ + 'true', 1.123, + ], + [ + '1', 'null', + ], ]; foreach ($rows as $row) { @@ -70,6 +85,11 @@ public function testWrite() '"column with enclosure "", and comma inside text","second column enclosure in text """', "\"columns with\nnew line\",\"columns with\ttab\"", '"column with \\n \\t \\\\","second col"', + '"1","1"', + '"2","0"', + '"3",""', + '"true","1.123"', + '"1","null"', '', ] ),