Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
43.10% covered (danger)
43.10%
50 / 116
14.29% covered (danger)
14.29%
1 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
LCP_Optimize_Bg_Image
43.10% covered (danger)
43.10%
50 / 116
14.29% covered (danger)
14.29%
1 / 7
334.70
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 preload_background_images
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 print_preload_links
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 add_bg_style_override
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
72
 get_responsive_image_rules
87.18% covered (warning)
87.18%
34 / 39
0.00% covered (danger)
0.00%
0 / 1
17.61
 get_image_set
88.24% covered (warning)
88.24%
15 / 17
0.00% covered (danger)
0.00%
0 / 1
4.03
1<?php
2
3namespace Automattic\Jetpack_Boost\Modules\Optimizations\Lcp;
4
5use Automattic\Jetpack\Image_CDN\Image_CDN_Core;
6
7class LCP_Optimize_Bg_Image {
8    /**
9     * The LCP data for optimizing the current page.
10     *
11     * @var array
12     */
13    private $lcp_data;
14
15    public static function init( $lcp_data ) {
16        if ( LCP_Optimization_Util::should_skip_optimization() ) {
17            return;
18        }
19
20        if ( empty( $lcp_data ) ) {
21            return;
22        }
23
24        $instance = new self( $lcp_data );
25
26        // Preload the background image as early as possible.
27        add_action( 'wp_head', array( $instance, 'preload_background_images' ), 1 );
28
29        // Add the background image styling as late as possible.
30        add_action( 'wp_body_open', array( $instance, 'add_bg_style_override' ), 999999 );
31    }
32
33    public function __construct( $lcp_data ) {
34        $this->lcp_data = $lcp_data;
35    }
36
37    public function preload_background_images() {
38        $selectors = array();
39
40        foreach ( $this->lcp_data as $lcp_data ) {
41            $lcp_optimizer = new LCP_Optimization_Util( $lcp_data );
42            if ( ! $lcp_optimizer->can_optimize() ) {
43                continue;
44            }
45
46            if ( in_array( $lcp_data['selector'], $selectors, true ) ) {
47                // If we already printed the styling for this element, skip it.
48                continue;
49            }
50            $selectors[] = $lcp_data['selector'];
51
52            $responsive_image_rules = $this->get_responsive_image_rules( $lcp_data );
53            $this->print_preload_links( $responsive_image_rules );
54        }
55    }
56
57    private function print_preload_links( $responsive_image_rules ) {
58        foreach ( $responsive_image_rules as $breakpoint ) {
59            $image_set = array();
60            foreach ( $breakpoint['image_set'] as $image ) {
61                $image_set[] = sprintf( '%s %sx', $image['url'], $image['dpr'] );
62            }
63
64            $image_set_string = implode( ', ', $image_set );
65
66            printf(
67                '<link rel="preload" href="%s" as="image" fetchpriority="high" media="%s" imagesrcset="%s" />' . PHP_EOL,
68                esc_url( Image_CDN_Core::cdn_url( $breakpoint['base_image'] ) ),
69                esc_attr( $breakpoint['media_query'] ),
70                esc_attr( $image_set_string )
71            );
72        }
73    }
74
75    public function add_bg_style_override() {
76        $selectors = array();
77
78        foreach ( $this->lcp_data as $lcp_data ) {
79            $lcp_optimizer = new LCP_Optimization_Util( $lcp_data );
80            if ( ! $lcp_optimizer->can_optimize() ) {
81                continue;
82            }
83
84            if ( in_array( $lcp_data['selector'], $selectors, true ) ) {
85                // If we already printed the styling for this element, skip it.
86                continue;
87            }
88            $selectors[] = $lcp_data['selector'];
89
90            $image_url = $lcp_optimizer->get_lcp_image_url();
91            if ( empty( $image_url ) ) {
92                continue;
93            }
94
95            $styles                 = array();
96            $responsive_image_rules = $this->get_responsive_image_rules( $lcp_data );
97
98            // Add responsive image styling.
99            foreach ( $responsive_image_rules as $breakpoint ) {
100                $image_set = array();
101                foreach ( $breakpoint['image_set'] as $image ) {
102                    $image_set[] = sprintf( 'url(%s) %sx', $image['url'], $image['dpr'] );
103                }
104
105                $image_set_string = implode( ', ', $image_set );
106
107                $styles[] = sprintf(
108                    '@media %1$s { %2$s { background-image: url(%3$s) !important; background-image: -webkit-image-set(%4$s) !important; background-image: image-set(%4$s) !important; } }',
109                    $breakpoint['media_query'],
110                    $lcp_data['selector'],
111                    $breakpoint['base_image'],
112                    $image_set_string
113                );
114            }
115
116            // Skip outputting empty style block when cssOverride is disabled.
117            if ( empty( $styles ) ) {
118                continue;
119            }
120
121            $bg_styling = PHP_EOL . '<style id="jetpack-boost-lcp-background-image">' . PHP_EOL;
122            // Ensure no </style> tag (or any HTML tags) in output.
123            $bg_styling .= wp_strip_all_tags( implode( PHP_EOL, $styles ) ) . PHP_EOL;
124            $bg_styling .= '</style>' . PHP_EOL;
125
126            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
127            echo $bg_styling;
128        }
129    }
130
131    private function get_responsive_image_rules( $lcp_data ) {
132        if ( $lcp_data['type'] !== LCP::TYPE_BACKGROUND_IMAGE || empty( $lcp_data['breakpoints'] ) ) {
133            return array();
134        }
135
136        // Check optimizations object from cloud.
137        // If cssOverride is false, skip all background-image optimizations (preload, !important CSS, resize URLs).
138        // This handles responsive backgrounds and custom focal points - the cloud determines what's safe.
139        // If no optimizations object exists (old cloud response), default to applying all optimizations.
140        if ( ! LCP_Optimization_Util::should_apply_optimization( $lcp_data, 'cssOverride' ) ) {
141            return array();
142        }
143
144        $lcp_optimizer = new LCP_Optimization_Util( $lcp_data );
145        $image_url     = $lcp_optimizer->get_lcp_image_url();
146
147        if ( empty( $image_url ) ) {
148            return array();
149        }
150
151        $styles = array();
152        // Reverse the array to go from smallest to largest.
153        foreach ( array_reverse( $lcp_data['breakpoints'] ) as $breakpoint ) {
154            if ( empty( $breakpoint ) ) {
155                continue;
156            }
157            if ( ! isset( $breakpoint['widthValue'] ) ) {
158                continue;
159            }
160
161            // The Cloud should always return a fixed pixel width for background images, so catering for that is easy peasy.
162            if ( empty( $breakpoint['imageDimensions'] ) || ! is_array( $breakpoint['imageDimensions'] ) ) {
163                continue;
164            }
165
166            $image_dimensions = $breakpoint['imageDimensions'][0];
167
168            if ( ! isset( $image_dimensions['width'] ) || ! is_numeric( $image_dimensions['width'] ) ) {
169                continue;
170            }
171
172            if ( ! isset( $image_dimensions['height'] ) || ! is_numeric( $image_dimensions['height'] ) ) {
173                continue;
174            }
175
176            // The width and height should already be an integer, but just in case.
177            $image_width  = (int) $image_dimensions['width'];
178            $image_height = (int) $image_dimensions['height'];
179
180            $media_query = array();
181            if ( isset( $breakpoint['minWidth'] ) ) {
182                $media_query[] = sprintf( '(min-width: %spx)', $breakpoint['minWidth'] );
183            }
184            if ( isset( $breakpoint['maxWidth'] ) ) {
185                $media_query[] = sprintf( '(max-width: %spx)', $breakpoint['maxWidth'] );
186            }
187
188            $styles[] = array(
189                'media_query' => empty( $media_query ) ? 'all' : implode( ' and ', $media_query ),
190                'image_set'   => $this->get_image_set( $image_url, $image_width, $image_height ),
191                'base_image'  => Image_CDN_Core::cdn_url(
192                    $image_url,
193                    array(
194                        'resize' => array( $image_width, $image_height ),
195                    )
196                ),
197            );
198        }
199        return $styles;
200    }
201
202    private function get_image_set( $url, $width, $height ) {
203        $dprs = array( 1, 2 );
204
205        // Mobile devices usually have a DPR of 3 which is not common for desktop.
206        if ( $width <= 480 ) {
207            $dprs[] = 3;
208        }
209
210        // Accurately reflect the performance improvement in lighthouse by including a 1.75x DPR image for the Moto G Power.
211        if ( $width === 412 ) {
212            $dprs[] = 1.75;
213        }
214
215        $image_set = array();
216        foreach ( $dprs as $dpr ) {
217            $image_set[] = array(
218                'url' => Image_CDN_Core::cdn_url(
219                    $url,
220                    array(
221                        'resize' => array( $width * $dpr, $height * $dpr ),
222                    )
223                ),
224                'dpr' => $dpr,
225            );
226        }
227        return $image_set;
228    }
229}