Extract is_registered and unregister

This commit is contained in:
Matt Sherman 2023-12-07 15:17:25 -05:00
parent 7206f2b3b9
commit 4dc0ac6432
2 changed files with 28 additions and 8 deletions

View File

@ -211,6 +211,30 @@ class BlockRegistry {
return $this->register_block_type_from_metadata( $block_json_file );
}
/**
* Check if a block is registered.
*
* @param string $block_name Block name.
*/
public function is_registered( $block_name ): bool {
$registry = \WP_Block_Type_Registry::get_instance();
return $registry->is_registered( $block_name );
}
/**
* Unregister a block.
*
* @param string $block_name Block name.
*/
public function unregister( $block_name ) {
$registry = \WP_Block_Type_Registry::get_instance();
if ( $registry->is_registered( $block_name ) ) {
$registry->unregister( $block_name );
}
}
/**
* Register a block type from metadata stored in the block.json file.
*
@ -235,11 +259,7 @@ class BlockRegistry {
return false;
}
$registry = \WP_Block_Type_Registry::get_instance();
if ( $registry->is_registered( $metadata['name'] ) ) {
$registry->unregister( $metadata['name'] );
}
$this->unregister( $metadata['name'] );
return register_block_type_from_metadata(
$metadata_file,

View File

@ -13,12 +13,12 @@ class BlockRegistryTest extends WC_Unit_Test_Case {
* Test registering a block type.
*/
public function test_register_block_type_from_metadata() {
$core_registry = \WP_Block_Type_Registry::get_instance();
$block_registry = BlockRegistry::get_instance();
$this->assertFalse( $block_registry->is_registered( 'woocommerce-test/test-block' ), 'Block type already registered.' );
$block_registry->register_block_type_from_metadata( trailingslashit( __DIR__ ) . 'test-block' );
$this->assertTrue( $core_registry->is_registered( 'woocommerce-test/test-block' ), 'Block type not registered.' );
$this->assertTrue( $block_registry->is_registered( 'woocommerce-test/test-block' ), 'Block type not registered.' );
}
}