Completed
Push — renovate/sirbrillig-phpcs-chan... ( ecf5f1...bc80b5 )
by Jeremy
125:13 queued 118:57
created

podcast-player.php ➔ get_css_vars()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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