[wp-trac] [WordPress Trac] #53936: Output of serialize_block_attributes does not match equivalent Gutenberg function

WordPress Trac noreply at wordpress.org
Mon Aug 16 19:10:54 UTC 2021


#53936: Output of serialize_block_attributes does not match equivalent Gutenberg
function
--------------------------+-----------------------------
 Reporter:  kevinfodness  |      Owner:  (none)
     Type:  defect (bug)  |     Status:  new
 Priority:  normal        |  Milestone:  Awaiting Review
Component:  General       |    Version:
 Severity:  normal        |   Keywords:
  Focuses:                |
--------------------------+-----------------------------
 In `wp-includes/blocks.php`, the serialize_block_attributes function runs
 `json_encode` with no options, which results in encoding all unicode
 elements and slashes. This behavior differs from Gutenberg's attribute
 serializer, which uses JSON.stringify, for which the default behavior does
 not encode slashes or unicode characters. In order to ensure that the two
 attribute serialization functions return the same output, I recommend
 using the options `JSON_UNESCAPED_UNICODE` and `JSON_UNESCAPED_SLASHES` in
 the PHP function.

 This example illustrates the differences in output between the two
 functions:

 {{{#!php
 <?php
 serialize_block_attributes( [ 'product' => 'Mike & Ike: €1.00 / 3 for
 €2.00' ] );
 // {"product":"Mike \u0026 Ike: \u20ac1.00 \/ 3 for \u20ac2.00"}
 }}}

 Versus JavaScript:

 {{{#!javascript
 serializeAttributes({ product: 'Mike & Ike: €1.00 / 3 for €2.00' });
 // {"product":"Mike \u0026 Ike: €1.00 / 3 for €2.00"}
 }}}

 In the PHP example, the forward slash and the Euro symbol are both
 escaped, but in JavaScript, they aren't.

 If we modify the flags in the `serialize_block_attributes` as follows:

 {{{#!php
 $encoded_attributes = json_encode( $block_attributes,
 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
 }}}

 Then the output matches what we get from the JavaScript function.

 I'll get working on a patch that both exposes this issue via a unit test
 and resolves it in the manner I proposed above, and I'll attach it here
 when I'm done.

 Related: Is there a reason why we are using `json_encode` here rather than
 `wp_json_encode`? As near as I can tell, this is the only location in
 WordPress core source code that uses `json_encode` other than the
 `wp_json_encode` function itself. Assuming this is in error, I'll make
 that change in my patch as well.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/53936>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list