Completed
Push — instant-search-master ( a786a9...893b7c )
by
unknown
85:32 queued 79:17
created

podcast-player.php ➔ render_block()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 0
loc 23
rs 9.552
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 Jetpack\Podcast_Player_Block;
11
12
use WP_Error;
13
use Jetpack_Gutenberg;
14
15
const FEATURE_NAME = 'podcast-player';
16
const BLOCK_NAME   = 'jetpack/' . FEATURE_NAME;
17
18
/**
19
 * Registers the block for use in Gutenberg
20
 * This is done via an action so that we can disable
21
 * registration if we need to.
22
 */
23
function register_block() {
24
	jetpack_register_block(
25
		BLOCK_NAME,
26
		array(
27
			'attributes'      => array(
28
				'url'                    => array(
29
					'type' => 'url',
30
				),
31
				'itemsToShow'            => array(
32
					'type'    => 'integer',
33
					'default' => 5,
34
				),
35
				'showCoverArt'           => array(
36
					'type'    => 'boolean',
37
					'default' => true,
38
				),
39
				'showEpisodeDescription' => array(
40
					'type'    => 'boolean',
41
					'default' => true,
42
				),
43
			),
44
			'render_callback' => __NAMESPACE__ . '\render_block',
45
		)
46
	);
47
}
48
add_action( 'init', __NAMESPACE__ . '\register_block' );
49
50
/**
51
 * Podcast Player block registration/dependency declaration.
52
 *
53
 * @param array $attributes Array containing the Podcast Player block attributes.
54
 * @return string
55
 */
56
function render_block( $attributes ) {
57
58
	// Test for empty URLS.
59
	if ( empty( $attributes['url'] ) ) {
60
		return '<p>' . esc_html__( 'No Podcast URL provided. Please enter a valid Podcast RSS feed URL.', 'jetpack' ) . '</p>';
61
	}
62
63
	// Test for invalid URLs.
64
	if ( ! wp_http_validate_url( $attributes['url'] ) ) {
65
		return '<p>' . esc_html__( 'Your podcast URL is invalid and couldn\'t be embedded. Please double check your URL.', 'jetpack' ) . '</p>';
66
	}
67
68
	// Sanitize the URL.
69
	$attributes['url'] = esc_url_raw( $attributes['url'] );
70
71
	$track_list = get_track_list( $attributes['url'], absint( $attributes['itemsToShow'] ) );
72
73
	if ( is_wp_error( $track_list ) ) {
74
		return '<p>' . esc_html( $track_list->get_error_message() ) . '</p>';
75
	}
76
77
	return render_player( $track_list, $attributes );
78
}
79
80
/**
81
 * Renders the HTML for the Podcast player and tracklist.
82
 *
83
 * @param array $track_list The list of podcast tracks.
84
 * @param array $attributes Array containing the Podcast Player block attributes.
85
 * @return string The HTML for the podcast player.
86
 */
87
function render_player( $track_list, $attributes ) {
88
	// If there are no tracks (it is possible) then display appropriate user facing error message.
89
	if ( empty( $track_list ) ) {
90
		return '<p>' . esc_html__( 'No tracks available to play.', 'jetpack' ) . '</p>';
91
	}
92
	$instance_id = wp_unique_id( 'podcast-player-block-' );
93
94
	$player_data = array(
95
		'tracks'     => $track_list,
96
		'attributes' => $attributes,
97
	);
98
99
	$block_classname = Jetpack_Gutenberg::block_classes( FEATURE_NAME, $attributes );
100
101
	ob_start();
102
	?>
103
	<div class="<?php echo esc_attr( $block_classname ); ?>" id="<?php echo esc_attr( $instance_id ); ?>">
104
		<ol>
105
			<?php
106
			foreach ( $track_list as $attachment ) :
107
				printf( '<li><a href="%1$s" data-jetpack-podcast-audio="%2$s">%3$s</a></li>', esc_url( $attachment['link'] ), esc_url( $attachment['src'] ), esc_html( $attachment['title'] ) );
108
			endforeach;
109
			?>
110
		</ol>
111
		<script type="application/json"><?php echo wp_json_encode( $player_data ); ?></script>
112
	</div>
113
	<script>window.jetpackPodcastPlayers=(window.jetpackPodcastPlayers||[]);window.jetpackPodcastPlayers.push( <?php echo wp_json_encode( $instance_id ); ?> );</script>
114
	<?php
115
	/*
116
	 * Enqueue necessary scripts and styles.
117
	 */
118
	wp_enqueue_style( 'wp-mediaelement' );
119
	Jetpack_Gutenberg::load_assets_as_required( 'podcast-player', array( 'wp-mediaelement' ) );
120
121
	return ob_get_clean();
122
}
123
124
/**
125
 * Gets a list of tracks for the supplied RSS feed.
126
 *
127
 * @param string $feed     The RSS feed to load and list tracks for.
128
 * @param int    $quantity Optional. The number of tracks to return.
129
 * @return array|WP_Error The feed's tracks or a error object.
130
 */
131
function get_track_list( $feed, $quantity = 10 ) {
132
	$rss = fetch_feed( $feed );
133
134
	if ( is_wp_error( $rss ) ) {
135
		return new WP_Error( 'invalid_url', __( 'Your podcast couldn\'t be embedded. Please double check your URL.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_url'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
136
	}
137
138
	if ( ! $rss->get_item_quantity() ) {
139
		return new WP_Error( 'no_tracks', __( 'Podcast audio RSS feed has no tracks.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_tracks'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
140
	}
141
142
	$track_list = array_map( __NAMESPACE__ . '\setup_tracks_callback', $rss->get_items( 0, $quantity ) );
143
144
	// Remove empty tracks.
145
	return \array_filter( $track_list );
146
}
147
148
/**
149
 * Prepares Episode data to be used with MediaElement.js.
150
 *
151
 * @param \SimplePie_Item $episode SimplePie_Item object, representing a podcast episode.
152
 * @return array
153
 */
154
function setup_tracks_callback( \SimplePie_Item $episode ) {
155
	$enclosure = $episode->get_enclosure();
156
157
	$url = ! empty( $episode->data['child']['']['enclosure'][0]['attribs']['']['url'] ) ? $episode->data['child']['']['enclosure'][0]['attribs']['']['url'] : null;
158
159
	// If there is no link return an empty array. We will filter out later.
160
	if ( ! $url ) {
161
		return array();
162
	}
163
164
	// Build track data.
165
	$track = array(
166
		'link'        => esc_url( $episode->get_link() ),
167
		'src'         => esc_url( $url ),
168
		'type'        => $enclosure->type,
169
		'caption'     => '',
170
		'description' => wp_kses_post( $episode->get_description() ),
171
		'meta'        => array(),
172
	);
173
174
	$track['title'] = esc_html( trim( wp_strip_all_tags( $episode->get_title() ) ) );
175
176
	if ( empty( $track['title'] ) ) {
177
		$track['title'] = esc_html__( '(no title)', 'jetpack' );
178
	}
179
180
	return $track;
181
}
182