• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Yoast / wordpress-seo / d6112f48a78380ef0e30c3424c33b8a053eaa052

14 Apr 2025 01:30PM UTC coverage: 52.454% (-2.1%) from 54.594%
d6112f48a78380ef0e30c3424c33b8a053eaa052

Pull #22077

github

web-flow
Merge 68bb84799 into b621a6397
Pull Request #22077: Drop compatibility with PHP 7.2 and 7.3

7827 of 13877 branches covered (56.4%)

Branch coverage included in aggregate %.

29025 of 56379 relevant lines covered (51.48%)

42277.18 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

12.86
/src/integrations/blocks/structured-data-blocks.php
1
<?php
2

3
namespace Yoast\WP\SEO\Integrations\Blocks;
4

5
use WPSEO_Admin_Asset_Manager;
6
use Yoast\WP\SEO\Conditionals\No_Conditionals;
7
use Yoast\WP\SEO\Helpers\Image_Helper;
8
use Yoast\WP\SEO\Integrations\Integration_Interface;
9

10
/**
11
 * Class to load assets required for structured data blocks.
12
 */
13
class Structured_Data_Blocks implements Integration_Interface {
14

15
        use No_Conditionals;
16

17
        /**
18
         * An instance of the WPSEO_Admin_Asset_Manager class.
19
         *
20
         * @var WPSEO_Admin_Asset_Manager
21
         */
22
        protected $asset_manager;
23

24
        /**
25
         * An instance of the image helper class.
26
         *
27
         * @var Image_Helper
28
         */
29
        protected $image_helper;
30

31
        /**
32
         * The image caches per post.
33
         *
34
         * @var array
35
         */
36
        protected $caches = [];
37

38
        /**
39
         * The used cache keys per post.
40
         *
41
         * @var array
42
         */
43
        protected $used_caches = [];
44

45
        /**
46
         * Whether or not we've registered our shutdown function.
47
         *
48
         * @var bool
49
         */
50
        protected $registered_shutdown_function = false;
51

52
        /**
53
         * Structured_Data_Blocks constructor.
54
         *
55
         * @param WPSEO_Admin_Asset_Manager $asset_manager The asset manager.
56
         * @param Image_Helper              $image_helper  The image helper.
57
         */
58
        public function __construct( WPSEO_Admin_Asset_Manager $asset_manager, Image_Helper $image_helper ) {
2✔
59
                $this->asset_manager = $asset_manager;
2✔
60
                $this->image_helper  = $image_helper;
2✔
61
        }
62

63
        /**
64
         * Registers hooks for Structured Data Blocks with WordPress.
65
         *
66
         * @return void
67
         */
68
        public function register_hooks() {
×
69
                $this->register_blocks();
×
70
        }
71

72
        /**
73
         * Registers the blocks.
74
         *
75
         * @return void
76
         */
77
        public function register_blocks() {
×
78
                /**
79
                 * Filter: 'wpseo_enable_structured_data_blocks' - Allows disabling Yoast's schema blocks entirely.
80
                 *
81
                 * @param bool $enable If false, our structured data blocks won't show.
82
                 */
83
                if ( ! \apply_filters( 'wpseo_enable_structured_data_blocks', true ) ) {
×
84
                        return;
×
85
                }
86

87
                \register_block_type(
×
88
                        \WPSEO_PATH . 'blocks/structured-data-blocks/faq/block.json',
×
89
                        [
×
90
                                'render_callback' => [ $this, 'optimize_faq_images' ],
×
91
                        ]
×
92
                );
×
93
                \register_block_type(
×
94
                        \WPSEO_PATH . 'blocks/structured-data-blocks/how-to/block.json',
×
95
                        [
×
96
                                'render_callback' => [ $this, 'optimize_how_to_images' ],
×
97
                        ]
×
98
                );
×
99
        }
100

101
        /**
102
         * Optimizes images in the FAQ blocks.
103
         *
104
         * @param array  $attributes The attributes.
105
         * @param string $content    The content.
106
         *
107
         * @return string The content with images optimized.
108
         */
109
        public function optimize_faq_images( $attributes, $content ) {
×
110
                if ( ! isset( $attributes['questions'] ) ) {
×
111
                        return $content;
×
112
                }
113

114
                return $this->optimize_images( $attributes['questions'], 'answer', $content );
×
115
        }
116

117
        /**
118
         * Transforms the durations into a translated string containing the count, and either singular or plural unit.
119
         * For example (in en-US): If 'days' is 1, it returns "1 day". If 'days' is 2, it returns "2 days".
120
         * If a number value is 0, we don't output the string.
121
         *
122
         * @param number $days    Number of days.
123
         * @param number $hours   Number of hours.
124
         * @param number $minutes Number of minutes.
125
         * @return array Array of pluralized durations.
126
         */
127
        private function transform_duration_to_string( $days, $hours, $minutes ) {
×
128
                $strings = [];
×
129
                if ( $days ) {
×
130
                        $strings[] = \sprintf(
×
131
                        /* translators: %d expands to the number of day/days. */
132
                                \_n( '%d day', '%d days', $days, 'wordpress-seo' ),
×
133
                                $days
×
134
                        );
×
135
                }
136
                if ( $hours ) {
×
137
                        $strings[] = \sprintf(
×
138
                        /* translators: %d expands to the number of hour/hours. */
139
                                \_n( '%d hour', '%d hours', $hours, 'wordpress-seo' ),
×
140
                                $hours
×
141
                        );
×
142
                }
143
                if ( $minutes ) {
×
144
                        $strings[] = \sprintf(
×
145
                        /* translators: %d expands to the number of minute/minutes. */
146
                                \_n( '%d minute', '%d minutes', $minutes, 'wordpress-seo' ),
×
147
                                $minutes
×
148
                        );
×
149
                }
150
                return $strings;
×
151
        }
152

153
        /**
154
         * Formats the durations into a translated string.
155
         *
156
         * @param array $attributes The attributes.
157
         * @return string The formatted duration.
158
         */
159
        private function build_duration_string( $attributes ) {
×
160
                $days            = ( $attributes['days'] ?? 0 );
×
161
                $hours           = ( $attributes['hours'] ?? 0 );
×
162
                $minutes         = ( $attributes['minutes'] ?? 0 );
×
163
                $elements        = $this->transform_duration_to_string( $days, $hours, $minutes );
×
164
                $elements_length = \count( $elements );
×
165

166
                switch ( $elements_length ) {
167
                        case 1:
×
168
                                return $elements[0];
×
169
                        case 2:
×
170
                                return \sprintf(
×
171
                                /* translators: %s expands to a unit of time (e.g. 1 day). */
172
                                        \__( '%1$s and %2$s', 'wordpress-seo' ),
×
173
                                        ...$elements
×
174
                                );
×
175
                        case 3:
×
176
                                return \sprintf(
×
177
                                /* translators: %s expands to a unit of time (e.g. 1 day). */
178
                                        \__( '%1$s, %2$s and %3$s', 'wordpress-seo' ),
×
179
                                        ...$elements
×
180
                                );
×
181
                        default:
182
                                return '';
×
183
                }
184
        }
185

186
        /**
187
         * Presents the duration text of the How-To block in the site language.
188
         *
189
         * @param array  $attributes The attributes.
190
         * @param string $content    The content.
191
         *
192
         * @return string The content with the duration text in the site language.
193
         */
194
        public function present_duration_text( $attributes, $content ) {
12✔
195
                $duration = $this->build_duration_string( $attributes );
12✔
196
                // 'Time needed:' is the default duration text that will be shown if a user doesn't add one.
197
                $duration_text = \__( 'Time needed:', 'wordpress-seo' );
12✔
198

199
                if ( isset( $attributes['durationText'] ) && $attributes['durationText'] !== '' ) {
12✔
200
                        $duration_text = $attributes['durationText'];
2✔
201
                }
202

203
                return \preg_replace(
12✔
204
                        '/(<p class="schema-how-to-total-time">)(<span class="schema-how-to-duration-time-text">.*<\/span>)(.[^\/p>]*)(<\/p>)/',
12✔
205
                        '<p class="schema-how-to-total-time"><span class="schema-how-to-duration-time-text">' . $duration_text . '&nbsp;</span>' . $duration . '</p>',
12✔
206
                        $content,
12✔
207
                        1
12✔
208
                );
12✔
209
        }
210

211
        /**
212
         * Optimizes images in the How-To blocks.
213
         *
214
         * @param array  $attributes The attributes.
215
         * @param string $content    The content.
216
         *
217
         * @return string The content with images optimized.
218
         */
219
        public function optimize_how_to_images( $attributes, $content ) {
2✔
220
                if ( ! isset( $attributes['steps'] ) ) {
2✔
221
                        return $content;
×
222
                }
223

224
                $content = $this->present_duration_text( $attributes, $content );
2✔
225

226
                return $this->optimize_images( $attributes['steps'], 'text', $content );
2✔
227
        }
228

229
        /**
230
         * Optimizes images in structured data blocks.
231
         *
232
         * @param array  $elements The list of elements from the block attributes.
233
         * @param string $key      The key in the data to iterate over.
234
         * @param string $content  The content.
235
         *
236
         * @return string The content with images optimized.
237
         */
238
        private function optimize_images( $elements, $key, $content ) {
×
239
                global $post;
×
240
                if ( ! $post ) {
×
241
                        return $content;
×
242
                }
243

244
                $this->add_images_from_attributes_to_used_cache( $post->ID, $elements, $key );
×
245

246
                // Then replace all images with optimized versions in the content.
247
                $content = \preg_replace_callback(
×
248
                        '/<img[^>]+>/',
×
249
                        function ( $matches ) {
×
250
                                \preg_match( '/src="([^"]+)"/', $matches[0], $src_matches );
×
251
                                if ( ! $src_matches || ! isset( $src_matches[1] ) ) {
×
252
                                        return $matches[0];
253
                                }
254
                                $attachment_id = $this->attachment_src_to_id( $src_matches[1] );
×
255
                                if ( $attachment_id === 0 ) {
×
256
                                        return $matches[0];
257
                                }
258
                                $image_size  = 'full';
×
259
                                $image_style = [ 'style' => 'max-width: 100%; height: auto;' ];
×
260
                                \preg_match( '/style="[^"]*width:\s*(\d+)px[^"]*"/', $matches[0], $style_matches );
×
261
                                if ( $style_matches && isset( $style_matches[1] ) ) {
×
262
                                        $width     = (int) $style_matches[1];
×
263
                                        $meta_data = \wp_get_attachment_metadata( $attachment_id );
×
264
                                        if ( isset( $meta_data['height'] ) && isset( $meta_data['width'] ) && $meta_data['height'] > 0 && $meta_data['width'] > 0 ) {
×
265
                                                $aspect_ratio = ( $meta_data['height'] / $meta_data['width'] );
×
266
                                                $height       = ( $width * $aspect_ratio );
×
267
                                                $image_size   = [ $width, $height ];
268
                                        }
269
                                        $image_style = '';
270
                                }
271

272
                                /**
273
                                 * Filter: 'wpseo_structured_data_blocks_image_size' - Allows adjusting the image size in structured data blocks.
274
                                 *
275
                                 * @since 18.2
276
                                 *
277
                                 * @param string|int[] $image_size     The image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order).
278
                                 * @param int          $attachment_id  The id of the attachment.
279
                                 * @param string       $attachment_src The attachment src.
280
                                 */
281
                                $image_size = \apply_filters(
×
282
                                        'wpseo_structured_data_blocks_image_size',
×
283
                                        $image_size,
×
284
                                        $attachment_id,
×
285
                                        $src_matches[1]
×
286
                                );
×
287
                                $image_html = \wp_get_attachment_image(
×
288
                                        $attachment_id,
×
289
                                        $image_size,
×
290
                                        false,
×
291
                                        $image_style
×
292
                                );
×
293

294
                                if ( empty( $image_html ) ) {
×
295
                                        return $matches[0];
296
                                }
297

298
                                return $image_html;
×
299
                        },
×
300
                        $content
×
301
                );
×
302

303
                if ( ! $this->registered_shutdown_function ) {
×
304
                        \register_shutdown_function( [ $this, 'maybe_save_used_caches' ] );
×
305
                        $this->registered_shutdown_function = true;
306
                }
307

308
                return $content;
309
        }
310

311
        /**
312
         * If the caches of structured data block images have been changed, saves them.
313
         *
314
         * @return void
315
         */
316
        public function maybe_save_used_caches() {
×
317
                foreach ( $this->used_caches as $post_id => $used_cache ) {
×
318
                        if ( isset( $this->caches[ $post_id ] ) && $used_cache === $this->caches[ $post_id ] ) {
×
319
                                continue;
320
                        }
321
                        \update_post_meta( $post_id, 'yoast-structured-data-blocks-images-cache', $used_cache );
322
                }
323
        }
324

325
        /**
326
         * Converts an attachment src to an attachment ID.
327
         *
328
         * @param string $src The attachment src.
329
         *
330
         * @return int The attachment ID. 0 if none was found.
331
         */
332
        private function attachment_src_to_id( $src ) {
×
333
                global $post;
334

335
                if ( isset( $this->used_caches[ $post->ID ][ $src ] ) ) {
×
336
                        return $this->used_caches[ $post->ID ][ $src ];
337
                }
338

339
                $cache = $this->get_cache_for_post( $post->ID );
×
340
                if ( isset( $cache[ $src ] ) ) {
×
341
                        $this->used_caches[ $post->ID ][ $src ] = $cache[ $src ];
×
342
                        return $cache[ $src ];
343
                }
344

345
                $this->used_caches[ $post->ID ][ $src ] = $this->image_helper->get_attachment_by_url( $src );
×
346
                return $this->used_caches[ $post->ID ][ $src ];
347
        }
348

349
        /**
350
         * Returns the cache from postmeta for a given post.
351
         *
352
         * @param int $post_id The post ID.
353
         *
354
         * @return array The images cache.
355
         */
356
        private function get_cache_for_post( $post_id ) {
×
357
                if ( isset( $this->caches[ $post_id ] ) ) {
×
358
                        return $this->caches[ $post_id ];
359
                }
360

361
                $cache = \get_post_meta( $post_id, 'yoast-structured-data-blocks-images-cache', true );
×
362
                if ( ! $cache ) {
×
363
                        $cache = [];
364
                }
365

366
                $this->caches[ $post_id ] = $cache;
×
367
                return $cache;
368
        }
369

370
        /**
371
         * Adds any images that have their ID in the block attributes to the cache.
372
         *
373
         * @param int    $post_id  The post ID.
374
         * @param array  $elements The elements.
375
         * @param string $key      The key in the elements we should loop over.
376
         *
377
         * @return void
378
         */
379
        private function add_images_from_attributes_to_used_cache( $post_id, $elements, $key ) {
×
380
                // First grab all image IDs from the attributes.
381
                $images = [];
×
382
                foreach ( $elements as $element ) {
×
383
                        if ( ! isset( $element[ $key ] ) ) {
×
384
                                continue;
385
                        }
386
                        if ( isset( $element[ $key ] ) && \is_array( $element[ $key ] ) ) {
×
387
                                foreach ( $element[ $key ] as $part ) {
×
388
                                        if ( ! \is_array( $part ) || ! isset( $part['type'] ) || $part['type'] !== 'img' ) {
×
389
                                                continue;
390
                                        }
391

392
                                        if ( ! isset( $part['key'] ) || ! isset( $part['props']['src'] ) ) {
×
393
                                                continue;
394
                                        }
395

396
                                        $images[ $part['props']['src'] ] = (int) $part['key'];
397
                                }
398
                        }
399
                }
400

401
                if ( isset( $this->used_caches[ $post_id ] ) ) {
×
402
                        $this->used_caches[ $post_id ] = \array_merge( $this->used_caches[ $post_id ], $images );
403
                }
404
                else {
405
                        $this->used_caches[ $post_id ] = $images;
406
                }
407
        }
408

409
        /* DEPRECATED METHODS */
410

411
        /**
412
         * Enqueue Gutenberg block assets for backend editor.
413
         *
414
         * @deprecated 22.7
415
         * @codeCoverageIgnore
416
         *
417
         * @return void
418
         */
419
        public function enqueue_block_editor_assets() {
420
                \_deprecated_function( __METHOD__, 'Yoast SEO 22.7' );
421
        }
422
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc