Completed
Push — fix/podcast-player-public-erro... ( d6b646 )
by
unknown
07:47
created

podcast-player.php ➔ render_error()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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