esc() for 'raw' context (Fixes #8624)

This commit is contained in:
Cleric-K 2024-03-18 11:26:02 +02:00
parent b8adef607e
commit c9a1bfec7a
No known key found for this signature in database
GPG Key ID: 8E367043A0556D81
2 changed files with 30 additions and 9 deletions

View File

@ -426,6 +426,15 @@ if (! function_exists('esc')) {
*/
function esc($data, string $context = 'html', ?string $encoding = null)
{
$context = strtolower($context);
// Provide a way to NOT escape data since
// this could be called automatically by
// the View library.
if ($context === 'raw') {
return $data;
}
if (is_array($data)) {
foreach ($data as &$value) {
$value = esc($value, $context);
@ -433,15 +442,6 @@ if (! function_exists('esc')) {
}
if (is_string($data)) {
$context = strtolower($context);
// Provide a way to NOT escape data since
// this could be called automatically by
// the View library.
if ($context === 'raw') {
return $data;
}
if (! in_array($context, ['html', 'js', 'css', 'url', 'attr'], true)) {
throw new InvalidArgumentException('Invalid escape context provided.');
}

View File

@ -247,6 +247,27 @@ final class CommonFunctionsTest extends CIUnitTestCase
esc('<script>', '0');
}
public function testEscapeArray(): void
{
$data = [
'a' => [
'b' => 'c&',
],
'd' => 'e>',
];
$expected = $data;
$expected['a']['b'] = 'c&amp;';
$expected['d'] = 'e&gt;';
$this->assertSame($expected, esc($data));
}
public function testEscapeRecursiveArrayRaw(): void
{
$data = ['a' => 'b', 'c' => 'd'];
$data['e'] = &$data;
$this->assertSame($data, esc($data, 'raw'));
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled