Skip to content

Commit 7d2e654

Browse files
committed
Factor out common logic to obtain valid src attribute
1 parent ebbf0d3 commit 7d2e654

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

plugins/image-prioritizer/class-image-prioritizer-img-tag-visitor.php

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,8 @@ public function __invoke( OD_Tag_Visitor_Context $context ): bool {
5353
* @return bool Whether the tag should be tracked in URL Metrics.
5454
*/
5555
private function process_img( OD_HTML_Tag_Processor $processor, OD_Tag_Visitor_Context $context ): bool {
56-
// Skip empty src attributes and data: URLs.
57-
$src = trim( (string) $processor->get_attribute( 'src' ) );
58-
if ( '' === $src || $this->is_data_url( $src ) ) {
56+
$src = $this->get_valid_src( $processor );
57+
if ( null === $src ) {
5958
return false;
6059
}
6160

@@ -247,9 +246,8 @@ private function process_picture( OD_HTML_Tag_Processor $processor, OD_Tag_Visit
247246

248247
// Process the IMG element within the PICTURE.
249248
if ( 'IMG' === $tag && ! $processor->is_tag_closer() ) {
250-
// Skip empty src attributes and data: URLs.
251-
$src = trim( (string) $processor->get_attribute( 'src' ) );
252-
if ( '' === $src || $this->is_data_url( $src ) ) {
249+
$src = $this->get_valid_src( $processor );
250+
if ( null === $src ) {
253251
return false;
254252
}
255253

@@ -283,6 +281,29 @@ private function process_picture( OD_HTML_Tag_Processor $processor, OD_Tag_Visit
283281
return false;
284282
}
285283

284+
/**
285+
* Gets valid src attribute value for preloading.
286+
*
287+
* Returns null if the src attribute is not a string (i.e. src was used as a boolean attribute was used), if it
288+
* it has an empty string value after trimming, or if it is a data: URL.
289+
*
290+
* @since n.e.x.t
291+
*
292+
* @param OD_HTML_Tag_Processor $processor Processor.
293+
* @return non-empty-string|null URL which is not a data: URL.
294+
*/
295+
private function get_valid_src( OD_HTML_Tag_Processor $processor ): ?string {
296+
$src = $processor->get_attribute( 'src' );
297+
if ( ! is_string( $src ) ) {
298+
return null;
299+
}
300+
$src = trim( $src );
301+
if ( '' === $src || $this->is_data_url( $src ) ) {
302+
return null;
303+
}
304+
return $src;
305+
}
306+
286307
/**
287308
* Adds a LINK with the supplied attributes for each viewport group when the provided XPath is the LCP element.
288309
*

0 commit comments

Comments
 (0)