function JsonEncoderTest::testHtmlUnsafeCharactersAreEscaped

Tests that HTML-unsafe characters are still escaped.

This ensures that existing JSON_HEX_* behavior is preserved after adding JSON_INVALID_UTF8_SUBSTITUTE.

File

core/modules/serialization/tests/src/Unit/Encoder/JsonEncoderTest.php, line 69

Class

JsonEncoderTest
Tests Drupal\serialization\Encoder\JsonEncoder.

Namespace

Drupal\Tests\serialization\Unit\Encoder

Code

public function testHtmlUnsafeCharactersAreEscaped() : void {
  $input = "<script>alert('test & \"hack\"');</script>";
  $encoded = $this->encoder
    ->encode($input, 'json');
  // Verify it's valid JSON.
  $this->assertJson($encoded, 'HTML-unsafe characters should produce valid JSON.');
  // Verify HTML-unsafe characters are escaped as hex codes.
  $this->assertStringContainsString('\\u003C', $encoded, '< should be escaped to \\u003C.');
  $this->assertStringContainsString('\\u003E', $encoded, '> should be escaped to \\u003E.');
  $this->assertStringContainsString('\\u0027', $encoded, "' should be escaped to \\u0027.");
  $this->assertStringContainsString('\\u0026', $encoded, '& should be escaped to \\u0026.');
  $this->assertStringContainsString('\\u0022', $encoded, '" should be escaped to \\u0022.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.