mirror of
https://github.com/gosticks/wordpress-develop.git
synced 2026-07-01 07:40:07 +00:00
General: Add optional callback argument to serialize_block(s).
Allow passing a function callback to serialize_block(s) that is invoked on each node in the tree of parsed blocks as it is traversed for serialization. A function argument was chosen for passing the callback function as it reflects a pattern familiar from other algorithms that apply a given callback function while traversing a data structure -- most notably PHP's own `array_map()`. Introducing a filter was considered as an alternative but ultimately dismissed. For a fairly low-level and general-purpose function such as `serialize_block()`, using a filter to pass the callback seemed risky, as it also requires ''removing'' that filter after usage in order to prevent the callback from being accidentally applied when `serialize_block()` is called in an entirely different context. Introducing a separate function for applying a given operation during tree traversal (i.e. independently of serialization) was also considered but dismissed, as it would unnecessarily duplicate tree traversal. Props dlh, gziolo. Fixes #59327. See #59313. git-svn-id: https://develop.svn.wordpress.org/trunk@56557 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
@@ -54,4 +54,28 @@ class Tests_Blocks_Serialize extends WP_UnitTestCase {
|
||||
$this->assertSame( 'example', strip_core_block_namespace( 'core/example' ) );
|
||||
$this->assertSame( 'plugin/example', strip_core_block_namespace( 'plugin/example' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @ticket 59327
|
||||
*
|
||||
* @covers ::serialize_blocks
|
||||
*/
|
||||
public function test_callback_argument() {
|
||||
$markup = "<!-- wp:outer --><!-- wp:inner {\"key\":\"value\"} -->Example.<!-- /wp:inner -->\n\nExample.\n\n<!-- wp:void /--><!-- /wp:outer -->";
|
||||
$blocks = parse_blocks( $markup );
|
||||
|
||||
$actual = serialize_blocks( $blocks, array( __CLASS__, 'add_attribute_to_inner_block' ) );
|
||||
|
||||
$this->assertSame(
|
||||
"<!-- wp:outer --><!-- wp:inner {\"key\":\"value\",\"myattr\":\"myvalue\"} -->Example.<!-- /wp:inner -->\n\nExample.\n\n<!-- wp:void /--><!-- /wp:outer -->",
|
||||
$actual
|
||||
);
|
||||
}
|
||||
|
||||
public static function add_attribute_to_inner_block( $block ) {
|
||||
if ( 'core/inner' === $block['blockName'] ) {
|
||||
$block['attrs']['myattr'] = 'myvalue';
|
||||
}
|
||||
return $block;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user