Skip to content

Commit 4860127

Browse files
committed
Add CSV escaping function
1 parent 7e8b548 commit 4860127

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

php/utils.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2032,3 +2032,26 @@ function get_hook_description( $hook ) {
20322032
}
20332033
return null;
20342034
}
2035+
2036+
/**
2037+
* Escape a value for CSV output.
2038+
*
2039+
* Values that start with the following characters are escaping with a single
2040+
* quote: =, +, -, @, TAB (0x09) and CR (0x0D).
2041+
*
2042+
* @param string $value Value to escape.
2043+
* @return string Escaped value.
2044+
*/
2045+
function escape_csv_value( $value ) {
2046+
if (
2047+
in_array(
2048+
substr( $value, 0, 1 ),
2049+
[ '=', '+', '-', '@', "\t", "\r" ],
2050+
true
2051+
)
2052+
) {
2053+
return "'{$value}";
2054+
}
2055+
2056+
return $value;
2057+
}

tests/UtilsTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -914,6 +914,34 @@ public static function dataParseUrl() {
914914
];
915915
}
916916

917+
/**
918+
* @dataProvider dataEscapeCsvValue
919+
*/
920+
public function testEscapeCsvValue( $input, $expected ) {
921+
$this->assertEquals( $expected, Utils\escape_csv_value( $input ) );
922+
}
923+
924+
public static function dataEscapeCsvValue() {
925+
return [
926+
// Values starting with special characters that should be escaped.
927+
[ '=formula', "'=formula" ],
928+
[ '+positive', "'+positive" ],
929+
[ '-negative', "'-negative" ],
930+
[ '@mention', "'@mention" ],
931+
[ "\tindented", "'\tindented" ],
932+
[ "\rcarriage", "'\rcarriage" ],
933+
934+
// Values that should not be escaped.
935+
[ 'normal text', 'normal text' ],
936+
[ 'text with = in middle', 'text with = in middle' ],
937+
[ '123', '123' ],
938+
[ '', '' ],
939+
[ ' leading space', ' leading space' ],
940+
[ 'trailing space ', 'trailing space ' ],
941+
[ '=x==y=', "'=x==y=" ], // Only escapes when the first character is special
942+
];
943+
}
944+
917945
public function testReplacePathConstsAddSlashes() {
918946
$expected = "define( 'ABSPATH', dirname( 'C:\\\\Users\\\\test\'s\\\\site' ) . '/' );";
919947
$source = "define( 'ABSPATH', dirname( __FILE__ ) . '/' );";

0 commit comments

Comments
 (0)