From 1e0aa82a5d130b75fb8230c2fdc44719c79964d0 Mon Sep 17 00:00:00 2001 From: Hannes Papenberg Date: Mon, 24 Apr 2023 14:14:12 +0200 Subject: [PATCH] Adding OutputFilter::stringJSSafe() --- Tests/OutputFilterTest.php | 12 ++++++++++++ src/OutputFilter.php | 31 +++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/Tests/OutputFilterTest.php b/Tests/OutputFilterTest.php index 24bdd39d..de82aaf7 100644 --- a/Tests/OutputFilterTest.php +++ b/Tests/OutputFilterTest.php @@ -101,6 +101,18 @@ public function testLinkXhtmlSafe() ); } + /** + * Tests making strings safe for usage in JS + */ + public function testStringJSSafe() + { + $this->assertEquals( + '\u0054\u0065\u0073\u0074\u0020\u0073\u0074\u0072\u0069\u006e\u0067\u0020\u0045\u0073\u0070\u0061\u00f1\u006f\u006c\u0020\u0420\u0443\u0441\u0441\u043a\u0438\u0439\u0020\ud55c\uad6d\uc5b4\u0020\u{1f910}', + $this->object->stringJSSafe('Test string Español Русский 한국어 🤐'), + 'Should convert the string to unicode escaped string' + ); + } + /** * Tests filtering strings down to ASCII-7 lowercase URL text */ diff --git a/src/OutputFilter.php b/src/OutputFilter.php index 865285d4..c22b8a05 100644 --- a/src/OutputFilter.php +++ b/src/OutputFilter.php @@ -89,6 +89,37 @@ function ($m) ); } + /** + * Processes a string and escapes it for use in JavaScript + * + * @param string $string String to process + * + * @return string Processed text + * + * @since 3.0 + */ + public static function stringJSSafe($string) + { + $chars = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY); + $newStr = ''; + + foreach ($chars as $chr) + { + $code = str_pad(dechex(StringHelper::ord($chr)), 4, '0', STR_PAD_LEFT); + + if (strlen($code) < 5) + { + $newStr .= '\\u' . $code; + } + else + { + $newStr .= '\\u{' . $code . '}'; + } + } + + return $newStr; + } + /** * Generates a URL safe version of the specified string with language transliteration. *