Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
93.84% |
137 / 146 |
|
50.00% |
6 / 12 |
CRAP | |
0.00% |
0 / 1 |
| LCP_Optimize_Img_Tag | |
93.84% |
137 / 146 |
|
50.00% |
6 / 12 |
86.69 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| optimize_buffer | |
90.91% |
10 / 11 |
|
0.00% |
0 / 1 |
5.02 | |||
| optimize_image | |
88.46% |
23 / 26 |
|
0.00% |
0 / 1 |
11.19 | |||
| is_attachment_size | |
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
12 | |||
| add_responsive_image_attributes | |
90.91% |
10 / 11 |
|
0.00% |
0 / 1 |
6.03 | |||
| get_object_fit | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
6 | |||
| get_marked_object_fit | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
5 | |||
| get_aspect_ratio | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
5 | |||
| to_dimension | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
6 | |||
| get_srcset | |
94.74% |
36 / 38 |
|
0.00% |
0 / 1 |
17.04 | |||
| reduce_widths | |
88.89% |
8 / 9 |
|
0.00% |
0 / 1 |
3.01 | |||
| get_sizes | |
88.89% |
8 / 9 |
|
0.00% |
0 / 1 |
8.09 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Automattic\Jetpack_Boost\Modules\Optimizations\Lcp; |
| 4 | |
| 5 | use Automattic\Jetpack\Image_CDN\Image_CDN; |
| 6 | use Automattic\Jetpack\Image_CDN\Image_CDN_Core; |
| 7 | use WP_HTML_Tag_Processor; |
| 8 | |
| 9 | class LCP_Optimize_Img_Tag { |
| 10 | |
| 11 | /** |
| 12 | * LCP data. |
| 13 | * |
| 14 | * @var array |
| 15 | */ |
| 16 | private $lcp_data; |
| 17 | |
| 18 | public function __construct( $lcp_data ) { |
| 19 | $this->lcp_data = $lcp_data; |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * Optimize a viewport's LCP HTML. |
| 24 | * |
| 25 | * @param string $buffer The buffer/html to optimize. |
| 26 | * @return string The optimized buffer, or the original buffer if no optimization was needed |
| 27 | * |
| 28 | * @since 4.0.0 |
| 29 | */ |
| 30 | public function optimize_buffer( $buffer ) { |
| 31 | $optimization_util = new LCP_Optimization_Util( $this->lcp_data ); |
| 32 | if ( ! $optimization_util->can_optimize() ) { |
| 33 | return $buffer; |
| 34 | } |
| 35 | |
| 36 | // Defensive check to ensure the LCP HTML is not empty. |
| 37 | if ( empty( $this->lcp_data['html'] ) ) { |
| 38 | return $buffer; |
| 39 | } |
| 40 | |
| 41 | // Only optimize if the type is one we know how to handle. |
| 42 | if ( $this->lcp_data['type'] !== LCP::TYPE_IMAGE ) { |
| 43 | return $buffer; |
| 44 | } |
| 45 | |
| 46 | $buffer_processor = $optimization_util->find_element( $buffer ); |
| 47 | if ( ! $buffer_processor ) { |
| 48 | return $buffer; |
| 49 | } |
| 50 | |
| 51 | // Create the optimized tag with required attributes. |
| 52 | return $this->optimize_image( $buffer_processor ); |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Optimize an image tag by adding required attributes. |
| 57 | * |
| 58 | * @param WP_HTML_Tag_Processor $buffer_processor The original HTML chunk of the page.. |
| 59 | * |
| 60 | * @return string The optimized buffer. |
| 61 | * |
| 62 | * @since 4.0.0 |
| 63 | */ |
| 64 | private function optimize_image( $buffer_processor ) { |
| 65 | // Check optimizations object for fetchpriority. |
| 66 | // If no optimizations object exists (old cloud response), default to applying. |
| 67 | $apply_fetchpriority = LCP_Optimization_Util::should_apply_optimization( $this->lcp_data, 'fetchpriority' ); |
| 68 | |
| 69 | if ( $apply_fetchpriority ) { |
| 70 | $buffer_processor->set_attribute( 'fetchpriority', 'high' ); |
| 71 | } |
| 72 | |
| 73 | // Check optimizations object for loading. |
| 74 | $apply_loading = LCP_Optimization_Util::should_apply_optimization( $this->lcp_data, 'loading' ); |
| 75 | |
| 76 | if ( $apply_loading ) { |
| 77 | $buffer_processor->set_attribute( 'loading', 'eager' ); |
| 78 | } |
| 79 | |
| 80 | $buffer_processor->set_attribute( 'data-jp-lcp-optimized', 'true' ); |
| 81 | |
| 82 | $image_url = $buffer_processor->get_attribute( 'src' ); |
| 83 | // Ensure the image URL is valid. |
| 84 | if ( ! wp_http_validate_url( $image_url ) ) { |
| 85 | return $buffer_processor->get_updated_html(); |
| 86 | } |
| 87 | |
| 88 | $resized_src = ''; |
| 89 | |
| 90 | // If the image isn't photonized, it might be resized by WP. |
| 91 | // We need the original image URL, as we'll be generating |
| 92 | // the necessary sizes based on it. |
| 93 | if ( ! Image_CDN_Core::is_cdn_url( $image_url ) ) { |
| 94 | $original_src = (string) $image_url; |
| 95 | $image_url = Image_CDN::strip_image_dimensions_maybe( $original_src ); |
| 96 | |
| 97 | // Its -WxH suffix names a WordPress size if stripping found the original, or the attachment lists it. |
| 98 | if ( $image_url !== $original_src || $this->is_attachment_size( $buffer_processor, $original_src ) ) { |
| 99 | $resized_src = $original_src; |
| 100 | } |
| 101 | } else { |
| 102 | // In case it's Photonized, we need to remove any size change arguments. |
| 103 | $image_url = remove_query_arg( array( 'w', 'h' ), $image_url ); |
| 104 | } |
| 105 | |
| 106 | // Additional validation after cleaning. |
| 107 | if ( ! wp_http_validate_url( $image_url ) ) { |
| 108 | return $buffer_processor->get_updated_html(); |
| 109 | } |
| 110 | |
| 111 | // Check optimizations object for cdnUrl. |
| 112 | $apply_cdn = LCP_Optimization_Util::should_apply_optimization( $this->lcp_data, 'cdnUrl' ); |
| 113 | |
| 114 | if ( $apply_cdn ) { |
| 115 | $buffer_processor->set_attribute( 'src', Image_CDN_Core::cdn_url( $image_url ) ); |
| 116 | } |
| 117 | |
| 118 | // Check optimizations object for srcset. |
| 119 | // The cloud sets srcset to false when custom focal points are detected |
| 120 | // (resize would use center-crop, losing the author's object-position). |
| 121 | $apply_srcset = LCP_Optimization_Util::should_apply_optimization( $this->lcp_data, 'srcset' ); |
| 122 | |
| 123 | // srcset uses CDN URLs internally (via Image_CDN_Core::cdn_url), so skip if CDN is disabled. |
| 124 | if ( $apply_srcset && $apply_cdn ) { |
| 125 | $this->add_responsive_image_attributes( $buffer_processor, $image_url, $resized_src ); |
| 126 | } |
| 127 | |
| 128 | return $buffer_processor->get_updated_html(); |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Whether the image's attachment lists the src's file as one of its sizes, as when the |
| 133 | * original is offloaded or deleted and there is no file on disk to confirm it. |
| 134 | * |
| 135 | * @param WP_HTML_Tag_Processor $element The image tag. |
| 136 | * @param string $src The image src. |
| 137 | * @return bool |
| 138 | */ |
| 139 | private function is_attachment_size( $element, $src ) { |
| 140 | list( $width ) = Image_CDN::parse_dimensions_from_filename( $src ); |
| 141 | if ( ! $width ) { |
| 142 | return false; |
| 143 | } |
| 144 | |
| 145 | $attachment_id = 0; |
| 146 | foreach ( $element->class_list() ?? array() as $class_name ) { |
| 147 | if ( preg_match( '/^wp-image-([1-9][0-9]*)$/', $class_name, $matches ) ) { |
| 148 | $attachment_id = (int) $matches[1]; |
| 149 | break; |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | $meta = $attachment_id ? wp_get_attachment_metadata( $attachment_id ) : false; |
| 154 | if ( ! is_array( $meta ) || empty( $meta['sizes'] ) || ! is_array( $meta['sizes'] ) ) { |
| 155 | return false; |
| 156 | } |
| 157 | |
| 158 | $file = rawurldecode( wp_basename( (string) wp_parse_url( $src, PHP_URL_PATH ) ) ); |
| 159 | foreach ( $meta['sizes'] as $size ) { |
| 160 | if ( is_array( $size ) && isset( $size['file'] ) && $size['file'] === $file ) { |
| 161 | return true; |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | return false; |
| 166 | } |
| 167 | |
| 168 | /** |
| 169 | * Optimize an image tag by adding srcset and sizes attributes. |
| 170 | * |
| 171 | * @param WP_HTML_Tag_Processor $element The original image tag. |
| 172 | * @param string $image_url The image URL. |
| 173 | * @param string $resized_src The src, if its -WxH suffix names a WordPress size. |
| 174 | * @return WP_HTML_Tag_Processor The optimized image tag. |
| 175 | * |
| 176 | * @since 4.0.0 |
| 177 | */ |
| 178 | private function add_responsive_image_attributes( $element, $image_url, $resized_src = '' ) { |
| 179 | // is_array() as well as empty(): empty( 'not-an-array' ) is false, so a string |
| 180 | // breakpoints field would reach the foreach in get_srcset() and get_sizes(). |
| 181 | if ( empty( $this->lcp_data['breakpoints'] ) || ! is_array( $this->lcp_data['breakpoints'] ) ) { |
| 182 | return $element; |
| 183 | } |
| 184 | |
| 185 | $object_fit = $this->get_object_fit( $element ); |
| 186 | |
| 187 | // Under cover, a file cropped to the box shows the same picture and is smaller. |
| 188 | $aspect_ratio = 'cover' === $object_fit ? null : $this->get_aspect_ratio( $element, $resized_src ); |
| 189 | |
| 190 | $srcset = $this->get_srcset( $image_url, $aspect_ratio, 'contain' === $object_fit ); |
| 191 | if ( ! empty( $srcset ) ) { |
| 192 | $element->set_attribute( 'srcset', $srcset ); |
| 193 | } |
| 194 | |
| 195 | $sizes = $this->get_sizes(); |
| 196 | if ( ! empty( $sizes ) ) { |
| 197 | $element->set_attribute( 'sizes', $sizes ); |
| 198 | } |
| 199 | |
| 200 | return $element; |
| 201 | } |
| 202 | |
| 203 | /** |
| 204 | * Get the image's object-fit: the computed one the cloud reports, which sees stylesheets too, |
| 205 | * else the one the markup sets, for reports from before the cloud sent it. |
| 206 | * |
| 207 | * @param WP_HTML_Tag_Processor $element The image tag. |
| 208 | * @return string|null 'cover', 'contain', or null for any other fit. |
| 209 | */ |
| 210 | private function get_object_fit( $element ) { |
| 211 | $fit = $this->get_marked_object_fit( $element ); |
| 212 | |
| 213 | if ( isset( $this->lcp_data['objectFit'] ) && is_string( $this->lcp_data['objectFit'] ) ) { |
| 214 | $reported = strtolower( $this->lcp_data['objectFit'] ); |
| 215 | |
| 216 | // A template save doesn't redo the analysis, so when the markup disagrees, assume no fit: it never crops. |
| 217 | $fit = null === $fit || $fit === $reported ? $reported : null; |
| 218 | } |
| 219 | |
| 220 | return in_array( $fit, array( 'cover', 'contain' ), true ) ? $fit : null; |
| 221 | } |
| 222 | |
| 223 | /** |
| 224 | * Get the object-fit the markup sets, as core's Featured Image (inline style) and Cover |
| 225 | * (data-object-fit) blocks do. |
| 226 | * |
| 227 | * @param WP_HTML_Tag_Processor $element The image tag. |
| 228 | * @return string|null The fit, lowercased, or null if the markup sets none. |
| 229 | */ |
| 230 | private function get_marked_object_fit( $element ) { |
| 231 | // Inline style first: its last !important declaration, else its last, as CSS applies them. |
| 232 | $style = $element->get_attribute( 'style' ); |
| 233 | if ( is_string( $style ) && preg_match_all( '/(?:^|;)\s*object-fit\s*:\s*([a-z-]+)\s*(!important\s*)?(?=;|$)/i', $style, $matches ) ) { |
| 234 | $important = array_filter( $matches[2] ); |
| 235 | $fits = $important ? array_intersect_key( $matches[1], $important ) : $matches[1]; |
| 236 | return strtolower( end( $fits ) ); |
| 237 | } |
| 238 | |
| 239 | if ( 'cover' === $element->get_attribute( 'data-object-fit' ) ) { |
| 240 | return 'cover'; |
| 241 | } |
| 242 | |
| 243 | return null; |
| 244 | } |
| 245 | |
| 246 | /** |
| 247 | * Get the aspect ratio of the file the page asked for. |
| 248 | * |
| 249 | * @param WP_HTML_Tag_Processor $element The image tag. |
| 250 | * @param string $resized_src The src, if its -WxH suffix names a WordPress size. |
| 251 | * @return float|null Width divided by height, or null if neither source gives both. |
| 252 | */ |
| 253 | private function get_aspect_ratio( $element, $resized_src ) { |
| 254 | // The size's -WxH suffix first: the attributes can describe a different size than the file. |
| 255 | list( $width, $height ) = Image_CDN::parse_dimensions_from_filename( (string) $resized_src ); |
| 256 | if ( ! $width || ! $height ) { |
| 257 | $width = $element->get_attribute( 'width' ); |
| 258 | $height = $element->get_attribute( 'height' ); |
| 259 | } |
| 260 | |
| 261 | $width = $this->to_dimension( $width ); |
| 262 | $height = $this->to_dimension( $height ); |
| 263 | |
| 264 | return $width && $height ? $width / $height : null; |
| 265 | } |
| 266 | |
| 267 | /** |
| 268 | * Read a pixel size, as digits only like Image CDN does. |
| 269 | * |
| 270 | * @param mixed $value An attribute or filename value. |
| 271 | * @return int|null The size, or null if it is not a whole number from 1 to 65535. |
| 272 | */ |
| 273 | private function to_dimension( $value ) { |
| 274 | if ( is_int( $value ) ) { |
| 275 | $value = (string) $value; |
| 276 | } |
| 277 | |
| 278 | // The cap keeps the widened sizes below in int range. |
| 279 | if ( ! is_string( $value ) || ! ctype_digit( $value ) || (int) $value < 1 || (int) $value > 65535 ) { |
| 280 | return null; |
| 281 | } |
| 282 | |
| 283 | return (int) $value; |
| 284 | } |
| 285 | |
| 286 | /** |
| 287 | * Get the srcsets for an image. |
| 288 | * |
| 289 | * @param string $original_url The original image URL. |
| 290 | * @param float|null $aspect_ratio The image's width divided by its height, if known. |
| 291 | * @param bool $fit_inside Whether the image is drawn inside the box (object-fit: contain). |
| 292 | * @return string The srcset for the image. |
| 293 | * |
| 294 | * @since 4.1.0 |
| 295 | */ |
| 296 | private function get_srcset( $original_url, $aspect_ratio = null, $fit_inside = false ) { |
| 297 | $dimensions = array(); |
| 298 | foreach ( $this->lcp_data['breakpoints'] as $breakpoint ) { |
| 299 | // The field is optional; the background-image sibling has always carried |
| 300 | // this guard, and without it an absent one is a foreach() TypeError on |
| 301 | // wp_head. |
| 302 | if ( empty( $breakpoint['imageDimensions'] ) || ! is_array( $breakpoint['imageDimensions'] ) ) { |
| 303 | continue; |
| 304 | } |
| 305 | |
| 306 | foreach ( $breakpoint['imageDimensions'] as $breakpoint_dimensions ) { |
| 307 | if ( ! is_array( $breakpoint_dimensions ) ) { |
| 308 | continue; |
| 309 | } |
| 310 | |
| 311 | // isset() as well as is_numeric(): is_numeric( $absent ) is an undefined |
| 312 | // key warning before it is false. |
| 313 | if ( ! isset( $breakpoint_dimensions['width'] ) || ! isset( $breakpoint_dimensions['height'] ) ) { |
| 314 | continue; |
| 315 | } |
| 316 | |
| 317 | if ( ! is_numeric( $breakpoint_dimensions['width'] ) || ! is_numeric( $breakpoint_dimensions['height'] ) ) { |
| 318 | continue; |
| 319 | } |
| 320 | |
| 321 | $width = (int) $breakpoint_dimensions['width']; |
| 322 | $height = (int) $breakpoint_dimensions['height']; |
| 323 | |
| 324 | // Resize to the image's own proportions, covering the box or fitting inside it: a box |
| 325 | // shaped differently would otherwise be cropped into the file, where CSS cannot undo it. |
| 326 | $file_width = $width; |
| 327 | $file_height = $height; |
| 328 | if ( $aspect_ratio ) { |
| 329 | $width_at_box_height = (int) ceil( $height * $aspect_ratio ); |
| 330 | |
| 331 | $file_width = $fit_inside ? min( $width, $width_at_box_height ) : max( $width, $width_at_box_height ); |
| 332 | $file_height = (int) round( $file_width / $aspect_ratio ); |
| 333 | } |
| 334 | |
| 335 | // Keyed by the box width, not the file's: the w descriptors must match `sizes`, |
| 336 | // or object-fit: cover draws the widened file at a lower density than the DPR. |
| 337 | $add = function ( $dpr ) use ( &$dimensions, $width, $file_width, $file_height ) { |
| 338 | $dimensions[ (int) round( $width * $dpr ) ] = array( (int) round( $file_width * $dpr ), (int) round( $file_height * $dpr ) ); |
| 339 | }; |
| 340 | |
| 341 | $add( 1 ); |
| 342 | |
| 343 | // If it's a Moto G Power, include a 1.75 DPR for accurate lighthouse representation of the optimized image. |
| 344 | if ( isset( $breakpoint['maxWidth'] ) && $breakpoint['maxWidth'] === 412 ) { |
| 345 | $add( 1.75 ); |
| 346 | } |
| 347 | |
| 348 | // Include 2x DPR. |
| 349 | $add( 2 ); |
| 350 | |
| 351 | // If it's a mobile breakpoint, include 3x DPR. |
| 352 | if ( isset( $breakpoint['maxWidth'] ) && $breakpoint['maxWidth'] <= 480 ) { |
| 353 | $add( 3 ); |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | // Remove unnecessary widths to save some bytes in the HTML. |
| 359 | $reduced_widths = $this->reduce_widths( array_keys( $dimensions ) ); |
| 360 | |
| 361 | $srcset = array(); |
| 362 | foreach ( $reduced_widths as $width ) { |
| 363 | $srcset[] = Image_CDN_Core::cdn_url( |
| 364 | $original_url, |
| 365 | array( |
| 366 | 'resize' => $dimensions[ $width ], |
| 367 | ) |
| 368 | ) . " {$width}w"; |
| 369 | } |
| 370 | |
| 371 | return implode( ', ', $srcset ); |
| 372 | } |
| 373 | |
| 374 | /** |
| 375 | * Remove any width if we have another higher width that is within 20px. |
| 376 | * |
| 377 | * @param array $widths The widths to reduce. |
| 378 | * @return array The reduced widths. |
| 379 | */ |
| 380 | private function reduce_widths( $widths ) { |
| 381 | rsort( $widths ); |
| 382 | $reduced_widths = array(); |
| 383 | $previous_width = 999999; |
| 384 | foreach ( $widths as $width ) { |
| 385 | if ( $previous_width - 20 < $width ) { |
| 386 | continue; |
| 387 | } |
| 388 | |
| 389 | $previous_width = $width; |
| 390 | $reduced_widths[] = $width; |
| 391 | } |
| 392 | return $reduced_widths; |
| 393 | } |
| 394 | |
| 395 | /** |
| 396 | * Get the sizes for an image. |
| 397 | * |
| 398 | * @return string The sizes for the image. |
| 399 | * |
| 400 | * @since 4.1.0 |
| 401 | */ |
| 402 | private function get_sizes() { |
| 403 | $sizes = array(); |
| 404 | foreach ( $this->lcp_data['breakpoints'] as $breakpoint ) { |
| 405 | // is_string() as well as isset(): an array widthValue is a TypeError from |
| 406 | // preg_match(), inside the output buffer callback. |
| 407 | if ( ! isset( $breakpoint['widthValue'] ) || ! is_string( $breakpoint['widthValue'] ) || ! preg_match( '/^[0-9]+(?:\.[0-9]+)?(?:px|vw)$/', $breakpoint['widthValue'] ) ) { |
| 408 | continue; |
| 409 | } |
| 410 | |
| 411 | // Make sure minWidth is valid if set. |
| 412 | if ( isset( $breakpoint['minWidth'] ) && ! is_numeric( $breakpoint['minWidth'] ) ) { |
| 413 | continue; |
| 414 | } |
| 415 | |
| 416 | $min_width_query = isset( $breakpoint['minWidth'] ) ? '(min-width: ' . $breakpoint['minWidth'] . 'px) ' : ''; |
| 417 | |
| 418 | $sizes[] = $min_width_query . $breakpoint['widthValue']; |
| 419 | } |
| 420 | |
| 421 | return implode( ', ', $sizes ); |
| 422 | } |
| 423 | } |