Completed
Push — update/podcast-player-extract-... ( ca434a )
by
unknown
06:11
created

podcast-player.php ➔ render_block()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 7
nop 1
dl 0
loc 35
rs 8.7377
c 0
b 0
f 0
1
<?php
2
/**
3
 * Podcast Player Block.
4
 *
5
 * @since 8.4.0
6
 *
7
 * @package Jetpack
8
 */
9
10
namespace Automattic\Jetpack\Extensions\Podcast_Player;
11
12
use WP_Error;
13
use Jetpack_Gutenberg;
14
use Jetpack_Podcast_Helper;
15
use Jetpack_AMP_Support;
16
17
const FEATURE_NAME = 'podcast-player';
18
const BLOCK_NAME   = 'jetpack/' . FEATURE_NAME;
19
20
if ( ! class_exists( 'Jetpack_Podcast_Helper' ) ) {
21
	\jetpack_require_lib( 'class-jetpack-podcast-helper' );
22
}
23
24
/**
25
 * Registers the block for use in Gutenberg. This is done via an action so that
26
 * we can disable registration if we need to.
27
 */
28
function register_block() {
29
	jetpack_register_block(
30
		BLOCK_NAME,
31
		array(
32
			'attributes'      => array(
33
				'url'                    => array(
34
					'type' => 'url',
35
				),
36
				'itemsToShow'            => array(
37
					'type'    => 'integer',
38
					'default' => 5,
39
				),
40
				'showCoverArt'           => array(
41
					'type'    => 'boolean',
42
					'default' => true,
43
				),
44
				'showEpisodeDescription' => array(
45
					'type'    => 'boolean',
46
					'default' => true,
47
				),
48
			),
49
			'render_callback' => __NAMESPACE__ . '\render_block',
50
		)
51
	);
52
}
53
add_action( 'init', __NAMESPACE__ . '\register_block' );
54
55
/**
56
 * Podcast Player block registration/dependency declaration.
57
 *
58
 * @param array|object $attributes Podcast Player block attributes / WP_Block instance.
59
 * @return string
60
 */
61
function render_block( $attributes ) {
62
63
	// Test for empty URLS.
64
	if ( empty( $attributes['url'] ) ) {
65
		return '<p>' . esc_html__( 'No Podcast URL provided. Please enter a valid Podcast RSS feed URL.', 'jetpack' ) . '</p>';
66
	}
67
68
	// Test for invalid URLs.
69
	if ( ! wp_http_validate_url( $attributes['url'] ) ) {
70
		return '<p>' . esc_html__( 'Your podcast URL is invalid and couldn\'t be embedded. Please double check your URL.', 'jetpack' ) . '</p>';
71
	}
72
73
	// Sanitize the URL.
74
	$attributes['url'] = esc_url_raw( $attributes['url'] );
75
76
	$player_data = Jetpack_Podcast_Helper::get_player_data( $attributes['url'] );
77
78
	if ( is_wp_error( $player_data ) ) {
79
		return '<p>' . esc_html( $player_data->get_error_message() ) . '</p>';
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
80
	}
81
82
	/*
83
	 * Get the block attributes checking if `$attributes`
84
	 * is an array and it has defined a property.
85
	 *
86
	 * It handles the dual-behavior of argument
87
	 * of the callback_render() function, which
88
	 * was recently introduced by this Pull Request:
89
	 * https://github.com/WordPress/gutenberg/pull/21467
90
	 */
91
	$block_attributes = ! is_array( $attributes ) && isset( $attributes->attributes )
92
		? $attributes->attributes
93
		: $attributes;
94
	return render_player( $player_data, $block_attributes );
95
}
96
97
/**
98
 * Renders the HTML for the Podcast player and tracklist.
99
 *
100
 * @param array $player_data The player data details.
101
 * @param array $attributes Array containing the Podcast Player block attributes.
102
 * @return string The HTML for the podcast player.
103
 */
104
function render_player( $player_data, $attributes ) {
105
	// If there are no tracks (it is possible) then display appropriate user facing error message.
106
	if ( empty( $player_data['tracks'] ) ) {
107
		return '<p>' . esc_html__( 'No tracks available to play.', 'jetpack' ) . '</p>';
108
	}
109
110
	// Only use the amount of tracks requested.
111
	$player_data['tracks'] = array_slice(
112
		$player_data['tracks'],
113
		0,
114
		absint( $attributes['itemsToShow'] )
115
	);
116
117
	// Generate a unique id for the block instance.
118
	$instance_id             = wp_unique_id( 'jetpack-podcast-player-block-' );
119
	$player_data['playerId'] = $instance_id;
120
121
	// Generate object to be used as props for PodcastPlayer.
122
	$player_props = array_merge(
123
		// Add all attributes.
124
		array( 'attributes' => $attributes ),
125
		// Add all player data.
126
		$player_data
127
	);
128
129
	$primary_colors    = get_colors( 'primary', $attributes, 'color' );
130
	$secondary_colors  = get_colors( 'secondary', $attributes, 'color' );
131
	$background_colors = get_colors( 'background', $attributes, 'background-color' );
132
133
	$player_classes_name  = trim( "{$secondary_colors['class']} {$background_colors['class']}" );
134
	$player_inline_style  = trim( "{$secondary_colors['style']} ${background_colors['style']}" );
135
	$player_inline_style .= get_css_vars( $attributes );
136
137
	$block_classname = Jetpack_Gutenberg::block_classes( FEATURE_NAME, $attributes, array( 'is-default' ) );
138
	$is_amp          = ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() );
139
140
	ob_start();
141
	?>
142
	<div class="<?php echo esc_attr( $block_classname ); ?>" id="<?php echo esc_attr( $instance_id ); ?>">
143
		<section
144
			class="jetpack-podcast-player <?php echo esc_attr( $player_classes_name ); ?>"
145
			style="<?php echo esc_attr( $player_inline_style ); ?>"
146
		>
147
			<?php
148
			render(
149
				'podcast-header',
150
				array_merge(
151
					$player_props,
152
					array(
153
						'primary_colors' => $primary_colors,
154
						'player_id'      => $player_data['playerId'],
155
					)
156
				)
157
			);
158
			?>
159
			<ol class="jetpack-podcast-player__tracks">
160
				<?php foreach ( $player_data['tracks'] as $track_index => $attachment ) : ?>
161
					<?php
162
					render(
163
						'playlist-track',
164
						array(
165
							'is_active'        => 0 === $track_index,
166
							'attachment'       => $attachment,
167
							'primary_colors'   => $primary_colors,
168
							'secondary_colors' => $secondary_colors,
169
						)
170
					);
171
					?>
172
				<?php endforeach; ?>
173
			</ol>
174
		</section>
175
		<?php if ( ! $is_amp ) : ?>
176
		<script type="application/json"><?php echo wp_json_encode( $player_props ); ?></script>
177
		<?php endif; ?>
178
	</div>
179
	<?php if ( ! $is_amp ) : ?>
180
	<script>
181
		( function( instanceId ) {
182
			document.getElementById( instanceId ).classList.remove( 'is-default' );
183
			window.jetpackPodcastPlayers=(window.jetpackPodcastPlayers||[]);
184
			window.jetpackPodcastPlayers.push( instanceId );
185
		} )( <?php echo wp_json_encode( $instance_id ); ?> );
186
	</script>
187
	<?php endif; ?>
188
	<?php
189
	/**
190
	 * Enqueue necessary scripts and styles.
191
	 */
192
	if ( ! $is_amp ) {
193
		wp_enqueue_style( 'wp-mediaelement' );
194
	}
195
	Jetpack_Gutenberg::load_assets_as_required( FEATURE_NAME, array( 'mediaelement' ) );
196
197
	return ob_get_clean();
198
}
199
200
/**
201
 * Given the color name, block attributes and the CSS property,
202
 * the function will return an array with the `class` and `style`
203
 * HTML attributes to be used straight in the markup.
204
 *
205
 * @example
206
 * $color = get_colors( 'secondary', $attributes, 'border-color'
207
 *  => array( 'class' => 'has-secondary', 'style' => 'border-color: #333' )
208
 *
209
 * @param string $name     Color attribute name, for instance `primary`, `secondary`, ...
210
 * @param array  $attrs    Block attributes.
211
 * @param string $property Color CSS property, fo instance `color`, `background-color`, ...
212
 * @return array           Colors array.
213
 */
214
function get_colors( $name, $attrs, $property ) {
215
	$attr_color  = "{$name}Color";
216
	$attr_custom = 'custom' . ucfirst( $attr_color );
217
218
	$color        = isset( $attrs[ $attr_color ] ) ? $attrs[ $attr_color ] : null;
219
	$custom_color = isset( $attrs[ $attr_custom ] ) ? $attrs[ $attr_custom ] : null;
220
221
	$colors = array(
222
		'class' => '',
223
		'style' => '',
224
	);
225
226
	if ( $color || $custom_color ) {
227
		$colors['class'] .= "has-{$name}";
228
229
		if ( $color ) {
230
			$colors['class'] .= " has-{$color}-{$property}";
231
		} elseif ( $custom_color ) {
232
			$colors['style'] .= "{$property}: {$custom_color};";
233
		}
234
	}
235
236
	return $colors;
237
}
238
239
/**
240
 * It generates a string with CSS variables according to the
241
 * block colors, prefixing each one with `--jetpack-podcast-player'.
242
 *
243
 * @param array $attrs Podcast Block attributes object.
244
 * @return string      CSS variables depending on block colors.
245
 */
246
function get_css_vars( $attrs ) {
247
	$colors_name = array( 'primary', 'secondary', 'background' );
248
249
	$inline_style = '';
250
	foreach ( $colors_name as $color ) {
251
		$hex_color = 'hex' . ucfirst( $color ) . 'Color';
252
		if ( ! empty( $attrs[ $hex_color ] ) ) {
253
			$inline_style .= " --jetpack-podcast-player-{$color}: {$attrs[ $hex_color ]};";
254
		}
255
	}
256
	return $inline_style;
257
}
258
259
/**
260
 * Render the given template in server-side.
261
 * Important note:
262
 *    The $template_props array will be extracted.
263
 *    This means it will create a var for each array item.
264
 *    Keep it mind when using this param to pass
265
 *    properties to the template.
266
 *
267
 * @param string $name           Template name, available in `./templates` folder.
268
 * @param array  $template_props Template properties. Optional.
269
 * @param bool   $print          Render template. True as default.
270
 * @return false|string          HTML markup or false.
271
 */
272
function render( $name, $template_props = array(), $print = true ) {
273
	if ( ! strpos( $name, '.php' ) ) {
274
		$name = $name . '.php';
275
	}
276
277
	$template_path = dirname( __FILE__ ) . '/templates/' . $name;
278
279
	if ( ! file_exists( $template_path ) ) {
280
		return '';
281
	}
282
283
	/*
284
	 * Optionally provided an assoc array of data to pass to template.
285
	 * IMPORTANT: It will be extracted into variables.
286
	 */
287
	if ( is_array( $template_props ) ) {
288
		/*
289
		 * It ignores the `discouraging` sniffer rule for extract, since it's needed
290
		 * to make the templating system works.
291
		 */
292
		extract( $template_props ); // phpcs:ignore WordPress.PHP.DontExtract.extract_extract
293
	}
294
295
	if ( $print ) {
296
		include $template_path;
297
	} else {
298
		ob_start();
299
		include $template_path;
300
		$markup = ob_get_contents();
301
		ob_end_clean();
302
303
		return $markup;
304
	}
305
}
306