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

Yoast / wordpress-seo / 6987097851

25 Nov 2023 04:49AM UTC coverage: 49.206% (-0.1%) from 49.302%
6987097851

push

github

web-flow
Merge pull request #20878 from Yoast/JRF/ghactions-minor-tweak

GH Actions: update a few links in inline comments

15305 of 31104 relevant lines covered (49.21%)

4.03 hits per line

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

15.63
/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(
2✔
59
                WPSEO_Admin_Asset_Manager $asset_manager,
60
                Image_Helper $image_helper
61
        ) {
1✔
62
                $this->asset_manager = $asset_manager;
2✔
63
                $this->image_helper  = $image_helper;
2✔
64
        }
1✔
65

66
        /**
67
         * Registers hooks for Structured Data Blocks with WordPress.
68
         */
69
        public function register_hooks() {
×
70
                \add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_block_editor_assets' ] );
×
71
                $this->register_blocks();
×
72
        }
73

74
        /**
75
         * Registers the blocks.
76
         *
77
         * @return void
78
         */
79
        public function register_blocks() {
×
80
                \register_block_type(
×
81
                        'yoast/faq-block',
×
82
                        [
83
                                'render_callback' => [ $this, 'optimize_faq_images' ],
×
84
                                'attributes'      => [
85
                                        'className' => [
86
                                                'default' => '',
87
                                                'type'    => 'string',
88
                                        ],
89
                                        'questions' => [
90
                                                'type' => 'array',
91
                                        ],
92
                                        'additionalListCssClasses' => [
93
                                                'type' => 'string',
94
                                        ],
95
                                ],
96
                        ]
97
                );
98
                \register_block_type(
×
99
                        'yoast/how-to-block',
×
100
                        [
101
                                'render_callback' => [ $this, 'optimize_how_to_images' ],
×
102
                                'attributes'      => [
103
                                        'hasDuration' => [
104
                                                'type' => 'boolean',
105
                                        ],
106
                                        'days' => [
107
                                                'type' => 'string',
108
                                        ],
109
                                        'hours' => [
110
                                                'type' => 'string',
111
                                        ],
112
                                        'minutes' => [
113
                                                'type' => 'string',
114
                                        ],
115
                                        'description' => [
116
                                                'type'     => 'array',
117
                                                'source'   => 'children',
118
                                                'selector' => '.schema-how-to-description',
119
                                        ],
120
                                        'jsonDescription' => [
121
                                                'type' => 'string',
122
                                        ],
123
                                        'steps' => [
124
                                                'type' => 'array',
125
                                        ],
126
                                        'additionalListCssClasses' => [
127
                                                'type' => 'string',
128
                                        ],
129
                                        'unorderedList' => [
130
                                                'type' => 'boolean',
131
                                        ],
132
                                        'durationText' => [
133
                                                'type' => 'string',
134
                                        ],
135
                                        'defaultDurationText' => [
136
                                                'type' => 'string',
137
                                        ],
138
                                ],
139
                        ]
140
                );
141
        }
142

143
        /**
144
         * Enqueue Gutenberg block assets for backend editor.
145
         */
146
        public function enqueue_block_editor_assets() {
×
147
                /**
148
                 * Filter: 'wpseo_enable_structured_data_blocks' - Allows disabling Yoast's schema blocks entirely.
149
                 *
150
                 * @api bool If false, our structured data blocks won't show.
151
                 */
152
                if ( ! \apply_filters( 'wpseo_enable_structured_data_blocks', true ) ) {
×
153
                        return;
×
154
                }
155

156
                $this->asset_manager->enqueue_script( 'structured-data-blocks' );
×
157
                $this->asset_manager->enqueue_style( 'structured-data-blocks' );
×
158
        }
159

160
        /**
161
         * Optimizes images in the FAQ blocks.
162
         *
163
         * @param array  $attributes The attributes.
164
         * @param string $content    The content.
165
         *
166
         * @return string The content with images optimized.
167
         */
168
        public function optimize_faq_images( $attributes, $content ) {
×
169
                if ( ! isset( $attributes['questions'] ) ) {
×
170
                        return $content;
×
171
                }
172

173
                return $this->optimize_images( $attributes['questions'], 'answer', $content );
×
174
        }
175

176
        /**
177
         * Transforms the durations into a translated string containing the count, and either singular or plural unit.
178
         * For example (in en-US): If 'days' is 1, it returns "1 day". If 'days' is 2, it returns "2 days".
179
         * If a number value is 0, we don't output the string.
180
         *
181
         * @param number $days Number of days.
182
         * @param number $hours Number of hours.
183
         * @param number $minutes Number of minutes.
184
         * @return array Array of pluralized durations.
185
         */
186
        private function transform_duration_to_string( $days, $hours, $minutes ) {
×
187
                $strings = [];
×
188
                if ( $days ) {
×
189
                        $strings[] = \sprintf(
×
190
                        /* translators: %d expands to the number of day/days. */
191
                                \_n( '%d day', '%d days', $days, 'wordpress-seo' ),
×
192
                                $days
×
193
                        );
194
                }
195
                if ( $hours ) {
×
196
                        $strings[] = \sprintf(
×
197
                        /* translators: %d expands to the number of hour/hours. */
198
                                \_n( '%d hour', '%d hours', $hours, 'wordpress-seo' ),
×
199
                                $hours
×
200
                        );
201
                }
202
                if ( $minutes ) {
×
203
                        $strings[] = \sprintf(
×
204
                        /* translators: %d expands to the number of minute/minutes. */
205
                                \_n( '%d minute', '%d minutes', $minutes, 'wordpress-seo' ),
×
206
                                $minutes
×
207
                        );
208
                }
209
                return $strings;
×
210
        }
211

212
        /**
213
         * Formats the durations into a translated string.
214
         *
215
         * @param array $attributes The attributes.
216
         * @return string The formatted duration.
217
         */
218
        private function build_duration_string( $attributes ) {
×
219
                $days            = ( $attributes['days'] ?? 0 );
×
220
                $hours           = ( $attributes['hours'] ?? 0 );
×
221
                $minutes         = ( $attributes['minutes'] ?? 0 );
×
222
                $elements        = $this->transform_duration_to_string( $days, $hours, $minutes );
×
223
                $elements_length = count( $elements );
×
224

225
                switch ( $elements_length ) {
226
                        case 1:
×
227
                                return $elements[0];
×
228
                        case 2:
×
229
                                return \sprintf(
×
230
                                /* translators: %s expands to a unit of time (e.g. 1 day). */
231
                                        \__( '%1$s and %2$s', 'wordpress-seo' ),
×
232
                                        ...$elements
×
233
                                );
234
                        case 3:
×
235
                                return \sprintf(
×
236
                                /* translators: %s expands to a unit of time (e.g. 1 day). */
237
                                        \__( '%1$s, %2$s and %3$s', 'wordpress-seo' ),
×
238
                                        ...$elements
×
239
                                );
240
                        default:
241
                                return '';
×
242
                }
243
        }
244

245
        /**
246
         * Presents the duration text of the How-To block in the site language.
247
         *
248
         * @param array  $attributes The attributes.
249
         * @param string $content    The content.
250
         *
251
         * @return string The content with the duration text in the site language.
252
         */
253
        public function present_duration_text( $attributes, $content ) {
12✔
254
                $duration = $this->build_duration_string( $attributes );
12✔
255
                // 'Time needed:' is the default duration text that will be shown if a user doesn't add one.
256
                $duration_text = \__( 'Time needed:', 'wordpress-seo' );
12✔
257

258
                if ( isset( $attributes['durationText'] ) && $attributes['durationText'] !== '' ) {
12✔
259
                        $duration_text = $attributes['durationText'];
2✔
260
                }
261

262
                return \preg_replace(
12✔
263
                        '/(<p class="schema-how-to-total-time">)(<span class="schema-how-to-duration-time-text">.*<\/span>)(.[^\/p>]*)(<\/p>)/',
12✔
264
                        '<p class="schema-how-to-total-time"><span class="schema-how-to-duration-time-text">' . $duration_text . '&nbsp;</span>' . $duration . '</p>',
12✔
265
                        $content,
12✔
266
                        1
12✔
267
                );
6✔
268
        }
269

270
        /**
271
         * Optimizes images in the How-To blocks.
272
         *
273
         * @param array  $attributes The attributes.
274
         * @param string $content    The content.
275
         *
276
         * @return string The content with images optimized.
277
         */
278
        public function optimize_how_to_images( $attributes, $content ) {
2✔
279
                if ( ! isset( $attributes['steps'] ) ) {
2✔
280
                        return $content;
×
281
                }
282

283
                $content = $this->present_duration_text( $attributes, $content );
2✔
284

285
                return $this->optimize_images( $attributes['steps'], 'text', $content );
2✔
286
        }
287

288
        /**
289
         * Optimizes images in structured data blocks.
290
         *
291
         * @param array  $elements The list of elements from the block attributes.
292
         * @param string $key      The key in the data to iterate over.
293
         * @param string $content  The content.
294
         *
295
         * @return string The content with images optimized.
296
         */
297
        private function optimize_images( $elements, $key, $content ) {
×
298
                global $post;
×
299
                if ( ! $post ) {
×
300
                        return $content;
×
301
                }
302

303
                $this->add_images_from_attributes_to_used_cache( $post->ID, $elements, $key );
×
304

305
                // Then replace all images with optimized versions in the content.
306
                $content = \preg_replace_callback(
×
307
                        '/<img[^>]+>/',
×
308
                        function ( $matches ) {
309
                                \preg_match( '/src="([^"]+)"/', $matches[0], $src_matches );
×
310
                                if ( ! $src_matches || ! isset( $src_matches[1] ) ) {
×
311
                                        return $matches[0];
312
                                }
313
                                $attachment_id = $this->attachment_src_to_id( $src_matches[1] );
×
314
                                if ( $attachment_id === 0 ) {
×
315
                                        return $matches[0];
316
                                }
317
                                $image_size  = 'full';
×
318
                                $image_style = [ 'style' => 'max-width: 100%; height: auto;' ];
×
319
                                \preg_match( '/style="[^"]*width:\s*(\d+)px[^"]*"/', $matches[0], $style_matches );
×
320
                                if ( $style_matches && isset( $style_matches[1] ) ) {
×
321
                                        $width     = (int) $style_matches[1];
×
322
                                        $meta_data = \wp_get_attachment_metadata( $attachment_id );
×
323
                                        if ( isset( $meta_data['height'] ) && isset( $meta_data['width'] ) && $meta_data['height'] > 0 && $meta_data['width'] > 0 ) {
×
324
                                                $aspect_ratio = ( $meta_data['height'] / $meta_data['width'] );
×
325
                                                $height       = ( $width * $aspect_ratio );
×
326
                                                $image_size   = [ $width, $height ];
327
                                        }
328
                                        $image_style = '';
329
                                }
330

331
                                /**
332
                                 * Filter: 'wpseo_structured_data_blocks_image_size' - Allows adjusting the image size in structured data blocks.
333
                                 *
334
                                 * @since 18.2
335
                                 *
336
                                 * @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).
337
                                 * @param int          $attachment_id  The id of the attachment.
338
                                 * @param string       $attachment_src The attachment src.
339
                                 */
340
                                $image_size = \apply_filters(
×
341
                                        'wpseo_structured_data_blocks_image_size',
×
342
                                        $image_size,
×
343
                                        $attachment_id,
×
344
                                        $src_matches[1]
345
                                );
346
                                $image_html = \wp_get_attachment_image(
×
347
                                        $attachment_id,
×
348
                                        $image_size,
×
349
                                        false,
×
350
                                        $image_style
351
                                );
352

353
                                if ( empty( $image_html ) ) {
×
354
                                        return $matches[0];
355
                                }
356

357
                                return $image_html;
×
358
                        },
×
359
                        $content
360
                );
361

362
                if ( ! $this->registered_shutdown_function ) {
×
363
                        \register_shutdown_function( [ $this, 'maybe_save_used_caches' ] );
×
364
                        $this->registered_shutdown_function = true;
365
                }
366

367
                return $content;
368
        }
369

370
        /**
371
         * If the caches of structured data block images have been changed, saves them.
372
         *
373
         * @return void
374
         */
375
        public function maybe_save_used_caches() {
×
376
                foreach ( $this->used_caches as $post_id => $used_cache ) {
×
377
                        if ( isset( $this->caches[ $post_id ] ) && $used_cache === $this->caches[ $post_id ] ) {
×
378
                                continue;
379
                        }
380
                        \update_post_meta( $post_id, 'yoast-structured-data-blocks-images-cache', $used_cache );
381
                }
382
        }
383

384
        /**
385
         * Converts an attachment src to an attachment ID.
386
         *
387
         * @param string $src The attachment src.
388
         *
389
         * @return int The attachment ID. 0 if none was found.
390
         */
391
        private function attachment_src_to_id( $src ) {
×
392
                global $post;
393

394
                if ( isset( $this->used_caches[ $post->ID ][ $src ] ) ) {
×
395
                        return $this->used_caches[ $post->ID ][ $src ];
396
                }
397

398
                $cache = $this->get_cache_for_post( $post->ID );
×
399
                if ( isset( $cache[ $src ] ) ) {
×
400
                        $this->used_caches[ $post->ID ][ $src ] = $cache[ $src ];
×
401
                        return $cache[ $src ];
402
                }
403

404
                $this->used_caches[ $post->ID ][ $src ] = $this->image_helper->get_attachment_by_url( $src );
×
405
                return $this->used_caches[ $post->ID ][ $src ];
406
        }
407

408
        /**
409
         * Returns the cache from postmeta for a given post.
410
         *
411
         * @param int $post_id The post ID.
412
         *
413
         * @return array The images cache.
414
         */
415
        private function get_cache_for_post( $post_id ) {
×
416
                if ( isset( $this->caches[ $post_id ] ) ) {
×
417
                        return $this->caches[ $post_id ];
418
                }
419

420
                $cache = \get_post_meta( $post_id, 'yoast-structured-data-blocks-images-cache', true );
×
421
                if ( ! $cache ) {
×
422
                        $cache = [];
423
                }
424

425
                $this->caches[ $post_id ] = $cache;
×
426
                return $cache;
427
        }
428

429
        /**
430
         * Adds any images that have their ID in the block attributes to the cache.
431
         *
432
         * @param int    $post_id  The post ID.
433
         * @param array  $elements The elements.
434
         * @param string $key      The key in the elements we should loop over.
435
         *
436
         * @return void
437
         */
438
        private function add_images_from_attributes_to_used_cache( $post_id, $elements, $key ) {
×
439
                // First grab all image IDs from the attributes.
440
                $images = [];
×
441
                foreach ( $elements as $element ) {
×
442
                        if ( ! isset( $element[ $key ] ) ) {
×
443
                                continue;
444
                        }
445
                        if ( isset( $element[ $key ] ) && \is_array( $element[ $key ] ) ) {
×
446
                                foreach ( $element[ $key ] as $part ) {
×
447
                                        if ( ! \is_array( $part ) || ! isset( $part['type'] ) || $part['type'] !== 'img' ) {
×
448
                                                continue;
449
                                        }
450

451
                                        if ( ! isset( $part['key'] ) || ! isset( $part['props']['src'] ) ) {
×
452
                                                continue;
453
                                        }
454

455
                                        $images[ $part['props']['src'] ] = (int) $part['key'];
456
                                }
457
                        }
458
                }
459

460
                if ( isset( $this->used_caches[ $post_id ] ) ) {
×
461
                        $this->used_caches[ $post_id ] = \array_merge( $this->used_caches[ $post_id ], $images );
462
                }
463
                else {
464
                        $this->used_caches[ $post_id ] = $images;
465
                }
466
        }
467
}
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

© 2025 Coveralls, Inc