1<?php
2/**
3 * Server-side rendering of the `core/video` block.
4 *
5 * @package WordPress
6 */
7
8/**
9 * Renders the `core/video` block on the server to supply the width and height attributes from the attachment metadata.
10 *
11 * @since 6.9.0
12 *
13 * @phpstan-param array{ "id"?: positive-int } $attributes
14 *
15 * @param array $attributes The block attributes.
16 * @param string $content The block content.
17 * @return string The block content with the dimensions added.
18 */
19function render_block_core_video( array $attributes, string $content ): string {
20 // if the content lacks any video tag, abort.
21 if ( ! str_contains( $content, '<video' ) ) {
22 return $content;
23 }
24
25 // If the 'id' attribute is not populated for a video attachment, abort.
26 if (
27 ! isset( $attributes['id'] ) ||
28 ! is_int( $attributes['id'] ) ||
29 $attributes['id'] <= 0
30 ) {
31 return $content;
32 }
33
34 // If the 'id' attribute wasn't for an attachment, abort.
35 if ( get_post_type( $attributes['id'] ) !== 'attachment' ) {
36 return $content;
37 }
38
39 // Get the width and height metadata for the video, and abort if absent or invalid.
40 $metadata = wp_get_attachment_metadata( $attributes['id'] );
41 if (
42 ! isset( $metadata['width'], $metadata['height'] ) ||
43 ! ( is_int( $metadata['width'] ) && is_int( $metadata['height'] ) ) ||
44 ! ( $metadata['width'] > 0 && $metadata['height'] > 0 )
45 ) {
46 return $content;
47 }
48
49 // Locate the VIDEO tag to add the dimensions.
50 $p = new WP_HTML_Tag_Processor( $content );
51 if ( ! $p->next_tag( array( 'tag_name' => 'VIDEO' ) ) ) {
52 return $content;
53 }
54
55 $p->set_attribute( 'width', (string) $metadata['width'] );
56 $p->set_attribute( 'height', (string) $metadata['height'] );
57
58 /*
59 * The aspect-ratio style is needed due to an issue with the CSS spec: <https://github.com/w3c/csswg-drafts/issues/7524>.
60 * Note that a style rule using attr() like the following cannot currently be used:
61 *
62 * .wp-block-video video[width][height] {
63 * aspect-ratio: attr(width type(<number>)) / attr(height type(<number>));
64 * }
65 *
66 * This is because this attr() is yet only implemented in Chromium: <https://caniuse.com/css3-attr>.
67 */
68 $style = $p->get_attribute( 'style' );
69 if ( ! is_string( $style ) ) {
70 $style = '';
71 }
72 $aspect_ratio_style = sprintf( 'aspect-ratio: %d / %d;', $metadata['width'], $metadata['height'] );
73 $p->set_attribute( 'style', $aspect_ratio_style . $style );
74
75 return $p->get_updated_html();
76}
77
78/**
79 * Registers the `core/video` block on server.
80 *
81 * @since 6.9.0
82 */
83function register_block_core_video(): void {
84 register_block_type_from_metadata(
85 __DIR__ . '/video',
86 array(
87 'render_callback' => 'render_block_core_video',
88 )
89 );
90}
91add_action( 'init', 'register_block_core_video' );
92