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
61 changes: 33 additions & 28 deletions src/parser/content-parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,20 @@
* The content parser that would be used to transform a post into an array of blocks, along with their attributes.
*/
class ContentParser {
/**
* Records which block attributes core resolved from a binding with a non-null
* value. Used in apply_sourced_attributes() to preserve the binding value,
* including empty strings, zero, false, and values matching the default.
*
* An entry such as $resolved_bindings[ $block ]['content'] === true means use
* the bound content. Without that entry, source saved HTML or the default.
* Records are shared across parsers expanding synced patterns. Weak keys
* remove each record when its block instance is freed.
*
* @var \WeakMap<WP_Block, array<string, true>>|null
*/
Comment thread
ingeniumed marked this conversation as resolved.
Resolved
private static ?\WeakMap $resolved_bindings = null;

/**
* Synced patterns currently being expanded, keyed by pattern post ID
* (e.g. [ 27 => true, 31 => true ]). Add a pattern on entry and restore
Expand Down Expand Up @@ -285,8 +299,24 @@ public function render_parsed_block( array $parsed_block, int|null $post_id, arr

$context = apply_filters( 'render_block_context', $context, $parsed_block, null );

$block_instance = new WP_Block( $parsed_block, $context, $this->block_registry );
$block_instance->render();
$block_instance = new WP_Block( $parsed_block, $context, $this->block_registry );
self::$resolved_bindings ??= new \WeakMap();
$capture_binding = static function ( $value, $source, $args, $block, $attribute ) {
$resolved = self::$resolved_bindings[ $block ] ?? [];
if ( null === $value ) {
unset( $resolved[ $attribute ] );
} else {
$resolved[ $attribute ] = true;
}
self::$resolved_bindings[ $block ] = $resolved;
return $value;
};
add_filter( 'block_bindings_source_value', $capture_binding, PHP_INT_MAX, 5 );
try {
$block_instance->render();
} finally {
remove_filter( 'block_bindings_source_value', $capture_binding, PHP_INT_MAX );
}

return $block_instance;
}
Expand Down Expand Up @@ -395,7 +425,7 @@ protected function apply_sourced_attributes( WP_Block $block ): array {
$attribute_default_value = $block_attribute_definition['default'] ?? null;

// If the attribute was resolved from a block binding, skip.
if ( $this->has_successful_block_binding( $block_attribute_name, $block_attributes, $attribute_default_value ) ) {
if ( isset( self::$resolved_bindings[ $block ][ $block_attribute_name ] ) ) {
continue;
}

Expand Down Expand Up @@ -445,31 +475,6 @@ protected function apply_sourced_attributes( WP_Block $block ): array {
return $block_attributes;
}

/**
* Inspect the attribute to determine if it was resolved from a block binding.
*
* @param string $attribute_name Attribute name.
* @param array $attributes Block attributes.
* @param mixed $default_value Default value of the attribute.
*/
protected function has_successful_block_binding( string $attribute_name, array $attributes, mixed $default_value ): bool {
// No bindings defined.
if ( ! isset( $attributes['metadata']['bindings'] ) ) {
return false;
}

$attribute_value = $attributes[ $attribute_name ] ?? null;
$bindings = $attributes['metadata']['bindings'];

// If the attribute is empty or matches the default value, it was not resolved
// from a block binding.
if ( empty( $attribute_value ) || $attribute_value === $default_value ) {
return false;
}

return isset( $bindings[ $attribute_name ]['source'] ) || isset( $bindings['__default']['source'] );
}

/**
* Processes the source attributes of a block.
*
Expand Down
125 changes: 125 additions & 0 deletions tests/parser/test-binding-values.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<?php
/**
* Tests for resolved binding values and fallback behavior.
*
* @package vip-block-data-api
*/

namespace WPCOMVIP\BlockDataApi;

class BindingValuesTest extends RegistryTestCase {
/** @dataProvider value_provider */
public function test_core_binding_values_are_preserved( $value, $expected ) {
$calls = 0;
$this->register_block_bindings_source( 'test/value', [
'label' => 'Test value',
'get_value_callback' => static function () use ( $value, &$calls ) {
++$calls;
return $value;
},
] );
$html = '<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"test/value"}}}} --><p>Saved fallback</p><!-- /wp:paragraph -->';
$result = ( new ContentParser() )->parse( $html );
$this->assertSame( $expected, $result['blocks'][0]['attributes']['content'] );
$this->assertSame( 1, $calls );
}

public function value_provider() {
return [
'empty string' => [ '', '' ],
'string zero' => [ '0', '0' ],
'integer zero' => [ 0, 0 ],
'false' => [ false, false ],
'nonempty' => [ 'Resolved', 'Resolved' ],
'null fallback' => [ null, 'Saved fallback' ],
];
}

public function test_resolved_value_matching_default_is_preserved() {
$this->register_block_bindings_source( 'test/value', [
'label' => 'Empty alt',
'get_value_callback' => static function () {
return ''; },
] );
$html = '<!-- wp:image {"metadata":{"bindings":{"alt":{"source":"test/value"}}}} --><img src="/image.png" alt="Saved fallback" /><!-- /wp:image -->';
$result = ( new ContentParser() )->parse( $html );
$this->assertSame( '', $result['blocks'][0]['attributes']['alt'] );
}

public function test_missing_source_does_not_preserve_attribute_default() {
$html = '<!-- wp:image {"metadata":{"bindings":{"alt":{"source":"test/missing"}}}} --><img src="/image.png" alt="Saved fallback" /><!-- /wp:image -->';
$result = ( new ContentParser() )->parse( $html );
$this->assertSame( 'Saved fallback', $result['blocks'][0]['attributes']['alt'] );
}

public function test_unsupported_block_still_sources_html() {
$this->register_block_with_attributes( 'test/unsupported', [
'content' => [
'type' => 'string',
'source' => 'html',
'selector' => 'p',
'default' => '',
],
] );
$this->register_block_bindings_source( 'test/value', [
'label' => 'Unused binding',
'get_value_callback' => function () {
$this->fail( 'Core should not resolve this binding' ); },
] );
$html = '<!-- wp:test/unsupported {"metadata":{"bindings":{"content":{"source":"test/value"}}}} --><p>Saved fallback</p><!-- /wp:test/unsupported -->';
$result = ( new ContentParser() )->parse( $html );
$this->assertSame( 'Saved fallback', $result['blocks'][0]['attributes']['content'] );
}

public function test_empty_binding_inside_synced_pattern() {
$this->register_block_bindings_source( 'test/value', [
'label' => 'Empty content',
'get_value_callback' => static function () {
return ''; },
] );
$pattern = self::factory()->post->create( [
'post_type' => 'wp_block',
'post_status' => 'publish',
'post_content' => '<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"test/value"}}}} --><p>Saved fallback</p><!-- /wp:paragraph -->',
] );
$result = ( new ContentParser() )->parse( sprintf( '<!-- wp:block {"ref":%d} /-->', $pattern ) );
$this->assertSame( '', $result['blocks'][0]['innerBlocks'][0]['attributes']['content'] );
}

public function test_binding_filter_is_removed_after_a_throwing_source() {
$this->register_block_bindings_source( 'test/value', [
'label' => 'Throwing source',
'get_value_callback' => static function () {
throw new \RuntimeException( 'Binding failed' ); },
] );
$before = $GLOBALS['wp_filter']['block_bindings_source_value']->callbacks[ PHP_INT_MAX ] ?? [];
$result = ( new ContentParser() )->parse( '<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"test/value"}}}} --><p>Fallback</p><!-- /wp:paragraph -->' );
$this->assertWPError( $result );
$this->assertSame( $before, $GLOBALS['wp_filter']['block_bindings_source_value']->callbacks[ PHP_INT_MAX ] ?? [] );
}
/** @dataProvider filtered_value_provider */
public function test_final_filtered_binding_value_controls_fallback( $filtered, $expected ) {
$this->register_block_bindings_source( 'test/value', [
'label' => 'Filtered binding',
'get_value_callback' => static function () {
return 'Initial'; },
] );
$filter = static function () use ( $filtered ) {
return $filtered;
};
add_filter( 'block_bindings_source_value', $filter, 20 );
try {
$result = ( new ContentParser() )->parse( '<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"test/value"}}}} --><p>Saved fallback</p><!-- /wp:paragraph -->' );
$this->assertSame( $expected, $result['blocks'][0]['attributes']['content'] );
} finally {
remove_filter( 'block_bindings_source_value', $filter, 20 );
}
}

public function filtered_value_provider() {
return [
'empty' => [ '', '' ],
'null' => [ null, 'Saved fallback' ],
];
}
}