Given two spans of text, indicate if they represent identical block types.
Description
This function normalizes block types to account for implicit core namespacing.
Note! This function only returns valid results when the complete block types are represented in the span offsets and lengths. This means that the full optional namespace and block name must be represented in the input arguments.
Example:
0 5 10 15 20 25 30 35 40
$text = '<!-- wp:block --><!-- /wp:core/block -->';
true === WP_Block_Processor::are_equal_block_types( $text, 9, 5, $text, 27, 10 );
false === WP_Block_Processor::are_equal_block_types( $text, 9, 5, 'my/block', 0, 8 );Parameters
$a_textstringrequired- Text in which first block type appears.
$a_atintrequired- Byte offset into text in which first block type starts.
$a_lengthintrequired- Byte length of first block type.
$b_textstringrequired- Text in which second block type appears (may be the same as the first text).
$b_atintrequired- Byte offset into text in which second block type starts.
$b_lengthintrequired- Byte length of second block type.
Source
public static function are_equal_block_types( string $a_text, int $a_at, int $a_length, string $b_text, int $b_at, int $b_length ): bool {
$a_ns_length = strcspn( $a_text, '/', $a_at, $a_length );
$b_ns_length = strcspn( $b_text, '/', $b_at, $b_length );
$a_has_ns = $a_ns_length !== $a_length;
$b_has_ns = $b_ns_length !== $b_length;
// Both contain namespaces.
if ( $a_has_ns && $b_has_ns ) {
if ( $a_length !== $b_length ) {
return false;
}
$a_block_type = substr( $a_text, $a_at, $a_length );
return 0 === substr_compare( $b_text, $a_block_type, $b_at, $b_length );
}
if ( $a_has_ns ) {
$b_block_type = 'core/' . substr( $b_text, $b_at, $b_length );
return (
strlen( $b_block_type ) === $a_length &&
0 === substr_compare( $a_text, $b_block_type, $a_at, $a_length )
);
}
if ( $b_has_ns ) {
$a_block_type = 'core/' . substr( $a_text, $a_at, $a_length );
return (
strlen( $a_block_type ) === $b_length &&
0 === substr_compare( $b_text, $a_block_type, $b_at, $b_length )
);
}
// Neither contains a namespace.
if ( $a_length !== $b_length ) {
return false;
}
$a_name = substr( $a_text, $a_at, $a_length );
return 0 === substr_compare( $b_text, $a_name, $b_at, $b_length );
}
Changelog
| Version | Description |
|---|---|
| 6.9.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.