Skip to content
Closed
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
39 changes: 39 additions & 0 deletions lib/experimental/html/class-wp-html-tag-processor.php
Original file line number Diff line number Diff line change
Expand Up @@ -1412,6 +1412,45 @@ public function get_attribute( $name ) {
return html_entity_decode( $raw_value );
}

/**
* Returns parsed attributes matching a given prefix in the currently-opened tag.
*
* Example:
* <code>
* $p = new WP_HTML_Tag_Processor( '<div data-enabled class="test" data-test-id="14">Test</div>' );
* $p->next_tag( [ 'class_name' => 'test' ] ) === true;
* $p->get_attributes_by_prefix( 'data-' ) === array( 'data-enabled' => true, 'data-test-id' => '14' );
*
* $p->next_tag( [] ) === false;
* $p->get_attributes_by_prefix( 'data' ) === null;
* </code>
*
* @since 6.2.0
*
* @param string $prefix Prefix of attributes whose value is requested.
* @return array|null Associative array of matching attribute names and values, or `null` if not at a tag.
* Boolean attributes map to `true`.
*/
function get_attributes_by_prefix( $prefix ) {
if ( null === $this->tag_name_starts_at ) {
return null;
}

$comparable = strtolower( $prefix );
$matches = array_filter(
array_keys( $this->attributes ),
function( $attr ) use ( $comparable ) {
return str_starts_with( $attr, $comparable );
}
);

$results = array();
foreach ( $matches as $attr ) {
$results[ $attr ] = $this->get_attribute( $attr );
}
return $results;
}

/**
* Returns the lowercase name of the currently-opened tag.
*
Expand Down
15 changes: 15 additions & 0 deletions phpunit/html/wp-html-tag-processor-test.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,21 @@ public function test_attributes_parser_treats_slash_as_attribute_separator() {
$this->assertSame( 'test', $p->get_attribute( 'e' ), 'Accessing an existing e="test" did not return "test"' );
}

/**
* @covers WP_HTML_Tag_Processor::get_attributes_by_prefix
*/
public function test_get_attributes_by_prefix_returns_set_of_matching_attributes_in_lowercase() {
$p = new WP_HTML_Tag_Processor( '<div DATA-enabled class="test" data-test-ID="14">Test</div>' );
$p->next_tag();
$this->assertSame(
array(
'data-enabled' => true,
'data-test-id' => '14',
),
$p->get_attributes_by_prefix( 'data-' )
);
}

/**
* @ticket 56299
*
Expand Down