Skip to content

Commit

Permalink
Merge pull request #52 from keboola/adamvyborny-fix-writing-false-value
Browse files Browse the repository at this point in the history
Fix writing false value
  • Loading branch information
AdamVyborny authored Apr 6, 2023
2 parents 59dde98 + 283f002 commit b97eb09
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 5 deletions.
2 changes: 1 addition & 1 deletion phpstan-baseline-8+.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 6 additions & 3 deletions src/CsvWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
20 changes: 20 additions & 0 deletions tests/CsvWriteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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"',
'',
]
),
Expand Down

0 comments on commit b97eb09

Please sign in to comment.