Skip to content

Commit

Permalink
Improve escaping of values in CSV exports (#21719)
Browse files Browse the repository at this point in the history
* Improve escaping of values in CSV exports

* adjust tests
  • Loading branch information
sgiehl committed Oct 10, 2024
1 parent 0c5684b commit ee19276
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
7 changes: 6 additions & 1 deletion core/DataTable/Renderer/Csv.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,12 @@ public function formatValue($value)
if (is_string($value)) {
$value = str_replace(["\t"], ' ', $value);

if (strpos($value, '"') !== false || strpos($value, $this->separator) !== false) {
// surround value with double quotes if it contains a double quote or a commonly used separator
if (strpos($value, '"') !== false
|| strpos($value, $this->separator) !== false
|| strpos($value, ',') !== false
|| strpos($value, ';') !== false
) {
$value = '"' . str_replace('"', '""', $value) . '"';
}
}
Expand Down
9 changes: 6 additions & 3 deletions tests/PHPUnit/Unit/DataTable/Renderer/CSVTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,12 @@ public function testCSVRendererCorrectlyEscapesHeadersAndValues()
$dataTable = $this->_getDataTableSimpleWithCommasInCells();
$render = new Csv();
$render->setTable($dataTable);
$render->setSeparator('#');
$render->convertToUnicode = false;

$expected = '"col,1","col,2"
"val""1","val"",2"';
$expected = '"col,1"#"col;2"
"val""1"#"val"",2"
val#"val#2"';
$actual = $render->render();
$this->assertEquals($expected, $actual);
}
Expand Down Expand Up @@ -504,7 +506,8 @@ private function _getDataTableSimpleWithCommasInCells()
{
$table = new DataTable();
$table->addRowsFromSimpleArray(array(
array("col,1" => "val\"1", "col,2" => "val\",2")
array("col,1" => "val\"1", "col;2" => "val\",2"),
array("col,1" => "val", "col;2" => "val#2")
));
return $table;
}
Expand Down

0 comments on commit ee19276

Please sign in to comment.