Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/parser/block-additions/core-block.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,19 @@ class CoreBlock {
* @access private
*/
public static function init(): void {
add_filter( 'vip_block_data_api__sourced_block_inner_blocks', [ __CLASS__, 'get_inner_blocks' ], 5, 5 );
// WordPress 6.9+ expands synced patterns into retained inner blocks.
// On 6.8, load and render their children ourselves to extract attributes.
if ( version_compare( $GLOBALS['wp_version'], '6.9', '<' ) ) {
add_filter( 'vip_block_data_api__sourced_block_inner_blocks', [ __CLASS__, 'get_inner_blocks' ], 5, 4 );
}
add_filter( 'vip_block_data_api__sourced_block_result', [ __CLASS__, 'remove_content_array' ], 5, 2 );
}

/**
* Get the inner blocks of a synced pattern / reusable block. Intended for use
* with the `vip_block_data_api__sourced_block_inner_blocks` filter.
*
* Synced patterns are dynamic blocks, and core's method of rendering dynamic
* On WordPress 6.8, synced patterns are dynamic blocks, and rendering dynamic
* blocks severs the connection between the parent block and its inner blocks:
*
* https://github.com/WordPress/WordPress/blob/6.6.1/wp-includes/class-wp-block.php#L519
Expand All @@ -69,6 +73,12 @@ public static function get_inner_blocks( array $inner_blocks, string|null $block
return $inner_blocks;
}

// Match core's numeric ref validation before get_post() can coerce a
// rejected value such as "27abc" into a post ID and reopen a cycle.
if ( ! is_numeric( $parsed_block['attrs']['ref'] ) ) {
return [];
}

$context = [];

// Support synced pattern overrides. Copied and adapted from core:
Expand Down
59 changes: 45 additions & 14 deletions src/parser/content-parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@
* The content parser that would be used to transform a post into an array of blocks, along with their attributes.
*/
class ContentParser {
/**
* Synced patterns currently being expanded, keyed by pattern post ID
* (e.g. [ 27 => true, 31 => true ]). Add a pattern on entry and restore
* the previous ancestors on exit. If a reference is already an ancestor,
* stop expanding it to prevent a direct or indirect cycle.
*
* @var array
*/
Comment thread
ingeniumed marked this conversation as resolved.
Resolved
private $ancestor_pattern_ids = [];

/**
* Block registry instance
*
Expand Down Expand Up @@ -189,7 +199,13 @@ public function parse( $post_content, $post_id = null, $filter_options = [] ) {
// sourced attribute logic.
$rendered_block = $this->render_parsed_block( $block, $post_id );

return $this->source_block( $rendered_block, $filter_options );
$previous_ancestor_pattern_ids = $this->ancestor_pattern_ids;
$this->ancestor_pattern_ids = [];
try {
return $this->source_block( $rendered_block, $filter_options );
} finally {
$this->ancestor_pattern_ids = $previous_ancestor_pattern_ids;
}
}, $blocks );

$sourced_blocks = array_values( array_filter( $sourced_blocks ) );
Expand Down Expand Up @@ -308,20 +324,35 @@ protected function source_block( WP_Block $block, array $filter_options ): array
$inner_blocks = iterator_to_array( $block->inner_blocks );
}

/**
* Filters a block's inner blocks before recursive iteration.
*
* @param array $inner_blocks An array of inner block (WP_Block) instances.
* @param string|null $block_name Name of the parsed block, or null for non-block content.
* @param int $post_id Post ID associated with the parsed block.
* @param array $parsed_block Result of parse_blocks() for this block.
*/
$inner_blocks = apply_filters( 'vip_block_data_api__sourced_block_inner_blocks', $inner_blocks, $block_name, $this->post_id, $block->parsed_block );
$pattern_ref = 'core/block' === $block_name ? ( $block->attributes['ref'] ?? null ) : null;
Comment thread
ingeniumed marked this conversation as resolved.
Resolved
if ( null !== $pattern_ref && isset( $this->ancestor_pattern_ids[ $pattern_ref ] ) ) {
// Do not reopen a pattern after core's render-time recursion guard unwinds.
$sourced_inner_blocks = [];
} else {
$previous_ancestor_pattern_ids = $this->ancestor_pattern_ids;
if ( null !== $pattern_ref ) {
$this->ancestor_pattern_ids[ $pattern_ref ] = true;
}

// Recursively iterate over inner blocks.
$sourced_inner_blocks = array_values( array_filter( array_map( function ( $inner_block ) use ( $filter_options ) {
return $this->source_block( $inner_block, $filter_options );
}, $inner_blocks ) ) );
try {
/**
* Filters a block's inner blocks before recursive iteration.
*
* @param array $inner_blocks An array of inner block (WP_Block) instances.
* @param string|null $block_name Name of the parsed block, or null for non-block content.
* @param int $post_id Post ID associated with the parsed block.
* @param array $parsed_block Result of parse_blocks() for this block.
*/
$inner_blocks = apply_filters( 'vip_block_data_api__sourced_block_inner_blocks', $inner_blocks, $block_name, $this->post_id, $block->parsed_block );

// Recursively iterate over inner blocks.
$sourced_inner_blocks = array_values( array_filter( array_map( function ( $inner_block ) use ( $filter_options ) {
return $this->source_block( $inner_block, $filter_options );
}, $inner_blocks ) ) );
} finally {
$this->ancestor_pattern_ids = $previous_ancestor_pattern_ids;
}
}

// Only set innerBlocks if entries are present to match prior version behavior.
if ( ! empty( $sourced_inner_blocks ) ) {
Expand Down
138 changes: 138 additions & 0 deletions tests/parser/test-pattern-rendering.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<?php
/**
* Synced pattern rendering regressions.
*
* @package vip-block-data-api
*/

namespace WPCOMVIP\BlockDataApi;

class PatternRenderingTest extends RegistryTestCase {
private function create_pattern( $content ) {
return self::factory()->post->create( [
'post_type' => 'wp_block',
'post_status' => 'publish',
'post_content' => $content,
] );
}

private function reference( $id ) {
return sprintf( '<!-- wp:block {"ref":%d} /-->', $id );
}

public function test_core_pattern_children_are_reused_when_available() {
$renders = 0;
$this->register_block_with_attributes( 'test/counted', [], [
'render_callback' => static function () use ( &$renders ) {
++$renders;
return '<p>Dynamic</p>';
},
] );
$pattern = $this->create_pattern( '<!-- wp:group --><div class="wp-block-group"><!-- wp:test/counted /--></div><!-- /wp:group -->' );
$result = ( new ContentParser() )->parse( str_repeat( $this->reference( $pattern ), 2 ) );
$this->assertIsArray( $result );
$this->assertCount( 2, $result['blocks'] );
// The 6.8 compatibility path still renders again to resolve sourced children.
$this->assertSame( version_compare( $GLOBALS['wp_version'], '6.9', '<' ) ? 4 : 2, $renders );
foreach ( $result['blocks'] as $block ) {
$this->assertCount( 1, $block['innerBlocks'] );
$this->assertSame( 'core/group', $block['innerBlocks'][0]['name'] );
$this->assertSame( 'test/counted', $block['innerBlocks'][0]['innerBlocks'][0]['name'] );
}
}

/** @dataProvider cycle_provider */
public function test_pattern_cycles_terminate( $mutual ) {
$first = $this->create_pattern( '' );
$second = $mutual ? $this->create_pattern( $this->reference( $first ) ) : $first;
wp_update_post( [
'ID' => $first,
'post_content' => $this->reference( $second ),
] );
$visits = 0;
$guard = static function ( $blocks ) use ( &$visits ) {
if ( ++$visits > 8 ) {
throw new \RuntimeException( 'Pattern traversal did not terminate' );
}
return $blocks;
};
add_filter( 'vip_block_data_api__sourced_block_inner_blocks', $guard );
try {
$result = ( new ContentParser() )->parse( $this->reference( $first ) );
$this->assertIsArray( $result );
$block = $result['blocks'][0];
for ( $index = 0; $index < ( $mutual ? 2 : 1 ); ++$index ) {
$this->assertCount( 1, $block['innerBlocks'] );
$block = $block['innerBlocks'][0];
}
$this->assertArrayNotHasKey( 'innerBlocks', $block );
} finally {
remove_filter( 'vip_block_data_api__sourced_block_inner_blocks', $guard );
}
}

public function cycle_provider() {
return [
'self' => [ false ],
'mutual' => [ true ],
];
}

public function test_pattern_references_rejected_by_core_are_not_expanded() {
$pattern = $this->create_pattern( '' );
$ref = sprintf( '"%dabc"', $pattern );
wp_update_post( [
'ID' => $pattern,
'post_content' => '<!-- wp:block {"ref":' . $ref . '} /-->',
] );
$visits = 0;
$guard = static function ( $blocks ) use ( &$visits ) {
if ( ++$visits > 8 ) {
throw new \RuntimeException( 'Invalid pattern reference did not terminate' );
}
return $blocks;
};
add_filter( 'vip_block_data_api__sourced_block_inner_blocks', $guard, 1 );
try {
$result = ( new ContentParser() )->parse( $this->reference( $pattern ) );
$this->assertIsArray( $result );
$this->assertCount( 1, $result['blocks'][0]['innerBlocks'] );
$this->assertArrayNotHasKey( 'innerBlocks', $result['blocks'][0]['innerBlocks'][0] );
} finally {
remove_filter( 'vip_block_data_api__sourced_block_inner_blocks', $guard, 1 );
}
}

public function test_numeric_string_pattern_reference_is_expanded() {
$pattern = $this->create_pattern( '<!-- wp:paragraph --><p>Pattern content</p><!-- /wp:paragraph -->' );
$result = ( new ContentParser() )->parse( sprintf( '<!-- wp:block {"ref":"%d"} /-->', $pattern ) );
$this->assertIsArray( $result );
$this->assertSame( 'core/paragraph', $result['blocks'][0]['innerBlocks'][0]['name'] );
$this->assertSame( 'Pattern content', $result['blocks'][0]['innerBlocks'][0]['attributes']['content'] );
}

public function test_reentrant_parser_does_not_capture_unrelated_blocks() {
$other = $this->create_pattern( '<!-- wp:paragraph --><p>Unrelated</p><!-- /wp:paragraph -->' );
$this->register_block_with_attributes( 'test/reentrant', [], [
'render_callback' => function () use ( $other ) {
$result = ( new ContentParser() )->parse( $this->reference( $other ) );
$this->assertIsArray( $result );
return '<p>Dynamic</p>';
},
] );
$pattern = $this->create_pattern( '<!-- wp:test/reentrant /--><!-- wp:paragraph --><p>Expected</p><!-- /wp:paragraph -->' );
$result = ( new ContentParser() )->parse( $this->reference( $pattern ) );
$this->assertSame( [ 'test/reentrant', 'core/paragraph' ], array_column( $result['blocks'][0]['innerBlocks'], 'name' ) );
}

public function test_blocks_generated_inside_dynamic_callbacks_are_not_pattern_children() {
$this->register_block_with_attributes( 'test/generated', [], [
'render_callback' => static function () {
return do_blocks( '<!-- wp:paragraph --><p>Generated content</p><!-- /wp:paragraph -->' );
},
] );
$pattern = $this->create_pattern( '<!-- wp:test/generated /-->' );
$result = ( new ContentParser() )->parse( $this->reference( $pattern ) );
$this->assertSame( [ 'test/generated' ], array_column( $result['blocks'][0]['innerBlocks'], 'name' ) );
}
}