Completed
Push — add/videopress-src-core-video-... ( 71c8fc )
by
unknown
98:39 queued 89:54
created

render_video_block_with_videopress()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 2
dl 0
loc 26
rs 9.504
c 0
b 0
f 0
1
<?php
2
3
class VideoPress_Gutenberg {
4
5
	/**
6
	 * Initialize the VideoPress Gutenberg extension
7
	 */
8
	public static function init() {
9
		if ( self::should_initialize() ) {
10
			add_action( 'init', array( __CLASS__, 'register_video_block_with_videopress' ) );
11
		}
12
	}
13
14
	/**
15
	 * Check whether conditions indicate the VideoPress Gutenberg extension should be initialized
16
	 *
17
	 * @return bool
18
	 */
19
	public static function should_initialize() {
20
		// Should not initialize if Gutenberg is not available
21
		if ( ! function_exists( 'register_block_type' ) ) {
22
			return false;
23
		}
24
25
		// Should initialize if this is a WP.com site
26
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
27
			return true;
28
		}
29
30
		// Should not initialize if this is a Jetpack site but Jetpack is not active (unless the dev mode is enabled)
31
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
32
			return false;
33
		}
34
35
		// Should initialize by default
36
		return true;
37
	}
38
39
	/**
40
	 * Register the Jetpack Gutenberg extension that adds VideoPress support to the core video block.
41
	 */
42
	public static function register_video_block_with_videopress() {
43
		register_block_type( 'core/video', array(
44
			'render_callback' => array( __CLASS__, 'render_video_block_with_videopress' ),
45
		) );
46
	}
47
48
	/**
49
	 * Render the core video block replacing the src attribute with the VideoPress URL
50
	 *
51
	 * @param array  $attributes Array containing the video block attributes.
52
	 * @param string $content    String containing the video block content.
53
	 *
54
	 * @return string
55
	 */
56
	public function render_video_block_with_videopress( $attributes, $content ) {
57
		if ( ! isset( $attributes['id'] ) ) {
58
			return $content;
59
		}
60
61
		$blog_id = get_current_blog_id();
62
		$post_id = absint( $attributes['id'] );
63
		$videopress_id = video_get_info_by_blogpostid( $blog_id, $post_id )->guid;
64
		$videopress_data = videopress_get_video_details( $videopress_id );
65
66
		if ( empty( $videopress_data->files->hd->mp4 ) ) {
67
			return $content;
68
		}
69
70
		$videopress_url = $videopress_data->file_url_base->https . $videopress_data->files->hd->mp4;
71
72
		return preg_replace(
73
			'/src="([^"]+)/',
74
			sprintf(
75
				'src="%1$s',
76
				esc_attr( $videopress_url )
77
			),
78
			$content,
79
			1
80
		);
81
	}
82
}
83
84
VideoPress_Gutenberg::init();
85