Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Blocks: Refactor the check against self for block hooks
  • Loading branch information
gziolo committed Sep 18, 2023
commit cbcaf336300dd52bccea45d3b5f04bcb66b9c855
9 changes: 9 additions & 0 deletions src/wp-includes/class-wp-block-type.php
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,15 @@ public function set_props( $args ) {
$args = apply_filters( 'register_block_type_args', $args, $this->name );

foreach ( $args as $property_name => $property_value ) {
// Avoid infinite recursion in block hooks (hooking to itself).
if ( 'block_hooks' === $property_name && array_key_exists( $this->name, $property_value ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Cannot hook block to itself.' ),
'6.4.0'
);
unset( $property_value[ $this->name ] );
}
$this->$property_name = $property_value;
}
}
Expand Down
5 changes: 4 additions & 1 deletion tests/phpunit/data/blocks/notice/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@
"root": ".wp-block-notice"
},
"blockHooks": {
"core/post-content": "before"
"tests/before": "before",
"tests/after": "after",
"tests/first-child": "firstChild",
"tests/last-child": "lastChild"
},
"supports": {
"align": true,
Expand Down
34 changes: 32 additions & 2 deletions tests/phpunit/tests/blocks/register.php
Original file line number Diff line number Diff line change
Expand Up @@ -645,8 +645,13 @@ public function test_block_registers_with_metadata_fixture() {
'Block type should contain selectors from metadata.'
);
// @ticket 59346
$this->assertSame(
array( 'core/post-content' => 'before' ),
$this->assertSameSets(
array(
'tests/before' => 'before',
'tests/after' => 'after',
'tests/first-child' => 'first_child',
'tests/last-child' => 'last_child',
),
Comment on lines +649 to +654
Copy link
Contributor

Choose a reason for hiding this comment

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

👍

$result->block_hooks,
'Block type should contain block hooks from metadata.'
);
Expand Down Expand Up @@ -1069,4 +1074,29 @@ public function test_register_block_style_name_without_spaces() {
$actual = register_block_style( 'core/query', $block_styles );
$this->assertTrue( $actual );
}

/**
* @ticket 59346
*
* @covers ::register_block_type
*
* @expectedIncorrectUsage WP_Block_Type::set_props
*/
public function test_register_block_hooks_targeting_itself() {
$block_name = 'tests/block-name';
$block_type = register_block_type(
$block_name,
array(
'block_hooks' => array(
$block_name => 'first',
'tests/other-block' => 'last',
),
)
);

$this->assertSameSets(
array( 'tests/other-block' => 'last' ),
$block_type->block_hooks
);
}
}