Skip to content

Commit

Permalink
Interactivity API: Move Store's data encoding to the echo call (#51974
Browse files Browse the repository at this point in the history
)

* Move `json_enconde` to the `echo` call inside `render`

* Escape tags and ampersands in WP_Interactivity_Store output

* Fix expected and add missing commas
  • Loading branch information
DAreRodz authored Jul 24, 2023
1 parent 54f716a commit cdd4f8b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,6 @@ static function merge_data( $data ) {
self::$store = array_replace_recursive( self::$store, $data );
}

/**
* Serialize store data to JSON.
*
* @return string|false Serialized JSON data.
*/
static function serialize() {
// TODO: Escape?
return wp_json_encode( self::$store );
}

/**
* Reset the store data.
*/
Expand All @@ -71,7 +61,9 @@ static function render() {
if ( empty( self::$store ) ) {
return;
}
$store = self::serialize();
echo "<script id=\"wp-interactivity-store-data\" type=\"application/json\">$store</script>";
echo sprintf(
'<script id="wp-interactivity-store-data" type="application/json">%s</script>',
wp_json_encode( self::$store, JSON_HEX_TAG | JSON_HEX_AMP )
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,22 @@ public function test_store_should_be_correctly_rendered() {
$rendered
);
}

public function test_store_should_also_escape_tags_and_amps() {
WP_Interactivity_Store::merge_data(
array(
'state' => array(
'amps' => 'http://site.test/?foo=1&baz=2&bar=3',
'tags' => 'Do not do this: <!-- <script>',
),
)
);
ob_start();
WP_Interactivity_Store::render();
$rendered = ob_get_clean();
$this->assertSame(
'<script id="wp-interactivity-store-data" type="application/json">{"state":{"amps":"http:\/\/site.test\/?foo=1\u0026baz=2\u0026bar=3","tags":"Do not do this: \u003C!-- \u003Cscript\u003E"}}</script>',
$rendered
);
}
}

1 comment on commit cdd4f8b

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Flaky tests detected in cdd4f8b.
Some tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information.

🔍 Workflow run URL: https://github.com/WordPress/gutenberg/actions/runs/5643301501
📝 Reported issues:

Please sign in to comment.