Completed
Push — feature/external-media ( f87b50...048014 )
by
unknown
79:08 queued 71:40
created

Jetpack_Slideshow_Shortcode::shortcode_callback()   D

Complexity

Conditions 10
Paths 272

Size

Total Lines 104

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
nc 272
nop 1
dl 0
loc 104
rs 4.7466
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php //phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
3
use Automattic\Jetpack\Assets;
4
5
/**
6
 * Slideshow shortcode.
7
 * Adds a new "slideshow" gallery type when adding a gallery using the classic editor.
8
 *
9
 * @package Jetpack
10
 */
11
12
/**
13
 * Slideshow shortcode usage: [gallery type="slideshow"] or the older [slideshow]
14
 */
15
class Jetpack_Slideshow_Shortcode {
16
	/**
17
	 * Number of slideshows on a page.
18
	 *
19
	 * @var int
20
	 */
21
	public $instance_count = 0;
22
23
	/**
24
	 * Constructor
25
	 */
26
	public function __construct() {
27
		global $shortcode_tags;
28
29
		// Only if the slideshow shortcode has not already been defined.
30
		if ( ! array_key_exists( 'slideshow', $shortcode_tags ) ) {
31
			add_shortcode( 'slideshow', array( $this, 'shortcode_callback' ) );
32
		}
33
34
		// Only if the gallery shortcode has not been redefined.
35
		if ( isset( $shortcode_tags['gallery'] ) && 'gallery_shortcode' === $shortcode_tags['gallery'] ) {
36
			add_filter( 'post_gallery', array( $this, 'post_gallery' ), 1002, 2 );
37
			add_filter( 'jetpack_gallery_types', array( $this, 'add_gallery_type' ), 10 );
38
		}
39
	}
40
41
	/**
42
	 * Responds to the [gallery] shortcode, but not an actual shortcode callback.
43
	 *
44
	 * @param string $value An empty string if nothing has modified the gallery output, the output html otherwise.
45
	 * @param array  $attr  The shortcode attributes array.
46
	 *
47
	 * @return string The (un)modified $value
48
	 */
49
	public function post_gallery( $value, $attr ) {
50
		// Bail if somebody else has done something.
51
		if ( ! empty( $value ) ) {
52
			return $value;
53
		}
54
55
		// If [gallery type="slideshow"] have it behave just like [slideshow].
56
		if ( ! empty( $attr['type'] ) && 'slideshow' === $attr['type'] ) {
57
			return $this->shortcode_callback( $attr );
58
		}
59
60
		return $value;
61
	}
62
63
	/**
64
	 * Add the Slideshow type to gallery settings
65
	 *
66
	 * @see Jetpack_Tiled_Gallery::media_ui_print_templates
67
	 *
68
	 * @param array $types An array of types where the key is the value, and the value is the caption.
69
	 *
70
	 * @return array
71
	 */
72
	public function add_gallery_type( $types = array() ) {
73
		$types['slideshow'] = esc_html__( 'Slideshow', 'jetpack' );
74
75
		return $types;
76
	}
77
78
	/**
79
	 * Display shortcode.
80
	 *
81
	 * @param array $attr Shortcode attributes.
82
	 */
83
	public function shortcode_callback( $attr ) {
84
		$post_id = get_the_ID();
85
86
		$attr = shortcode_atts(
87
			array(
88
				'trans'     => 'fade',
89
				'order'     => 'ASC',
90
				'orderby'   => 'menu_order ID',
91
				'id'        => $post_id,
92
				'include'   => '',
93
				'exclude'   => '',
94
				'autostart' => true,
95
				'size'      => '',
96
			),
97
			$attr,
98
			'slideshow'
99
		);
100
101
		if ( 'rand' === strtolower( $attr['order'] ) ) {
102
			$attr['orderby'] = 'none';
103
		}
104
105
		$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
106
		if ( ! $attr['orderby'] ) {
107
			$attr['orderby'] = 'menu_order ID';
108
		}
109
110
		if ( ! $attr['size'] ) {
111
			$attr['size'] = 'full';
112
		}
113
114
		// Don't restrict to the current post if include.
115
		$post_parent = ( empty( $attr['include'] ) ) ? intval( $attr['id'] ) : null;
116
117
		$attachments = get_posts(
118
			array(
119
				'post_status'      => 'inherit',
120
				'post_type'        => 'attachment',
121
				'post_mime_type'   => 'image',
122
				'posts_per_page'   => - 1,
123
				'post_parent'      => $post_parent,
124
				'order'            => $attr['order'],
125
				'orderby'          => $attr['orderby'],
126
				'include'          => $attr['include'],
127
				'exclude'          => $attr['exclude'],
128
				'suppress_filters' => false,
129
			)
130
		);
131
132
		if ( count( $attachments ) < 1 ) {
133
			return false;
134
		}
135
136
		$gallery_instance = sprintf( 'gallery-%d-%d', $attr['id'], ++$this->instance_count );
137
138
		$gallery = array();
139
		foreach ( $attachments as $attachment ) {
140
			$attachment_image_src   = wp_get_attachment_image_src( $attachment->ID, $attr['size'] );
141
			$attachment_image_src   = $attachment_image_src[0]; // [url, width, height].
142
			$attachment_image_title = get_the_title( $attachment->ID );
143
			$attachment_image_alt   = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true );
144
			/**
145
			 * Filters the Slideshow slide caption.
146
			 *
147
			 * @module shortcodes
148
			 *
149
			 * @since 2.3.0
150
			 *
151
			 * @param string wptexturize( strip_tags( $attachment->post_excerpt ) ) Post excerpt.
152
			 * @param string $attachment ->ID Attachment ID.
153
			 */
154
			$caption = apply_filters( 'jetpack_slideshow_slide_caption', wptexturize( wp_strip_all_tags( $attachment->post_excerpt ) ), $attachment->ID );
155
156
			$gallery[] = (object) array(
157
				'src'      => (string) esc_url_raw( $attachment_image_src ),
158
				'id'       => (string) $attachment->ID,
159
				'title'    => (string) esc_attr( $attachment_image_title ),
160
				'alt'      => (string) esc_attr( $attachment_image_alt ),
161
				'caption'  => (string) $caption,
162
				'itemprop' => 'image',
163
			);
164
		}
165
166
		$color = Jetpack_Options::get_option( 'slideshow_background_color', 'black' );
167
168
		$js_attr = array(
169
			'gallery'   => $gallery,
170
			'selector'  => $gallery_instance,
171
			'trans'     => $attr['trans'] ? $attr['trans'] : 'fade',
172
			'autostart' => $attr['autostart'] ? $attr['autostart'] : 'true',
173
			'color'     => $color,
174
		);
175
176
		// Show a link to the gallery in feeds.
177
		if ( is_feed() ) {
178
			return sprintf(
179
				'<a href="%s">%s</a>',
180
				esc_url( get_permalink( $post_id ) . '#' . $gallery_instance . '-slideshow' ),
181
				esc_html__( 'Click to view slideshow.', 'jetpack' )
182
			);
183
		}
184
185
		return $this->slideshow_js( $js_attr );
186
	}
187
188
	/**
189
	 * Render the slideshow js
190
	 *
191
	 * Returns the necessary markup and js to fire a slideshow.
192
	 *
193
	 * @param array $attr Attributes for the slideshow.
194
	 *
195
	 * @uses $this->enqueue_scripts()
196
	 *
197
	 * @return string HTML output.
198
	 */
199
	public function slideshow_js( $attr ) {
200
		// Enqueue scripts.
201
		$this->enqueue_scripts();
202
203
		$output = '';
204
205
		if ( defined( 'JSON_HEX_AMP' ) ) {
206
			// This is nice to have, but not strictly necessary since we use _wp_specialchars() below.
207
			$gallery = wp_json_encode( $attr['gallery'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); // phpcs:ignore PHPCompatibility
208
		} else {
209
			$gallery = wp_json_encode( $attr['gallery'] );
210
		}
211
212
		$output .= '<p class="jetpack-slideshow-noscript robots-nocontent">' . esc_html__( 'This slideshow requires JavaScript.', 'jetpack' ) . '</p>';
213
214
		/*
215
		 * The input to json_encode() above can contain '&quot;'.
216
		 *
217
		 * For calls to json_encode() lacking the JSON_HEX_AMP option,
218
		 * that '&quot;' is left unaltered.  Running '&quot;' through esc_attr()
219
		 * also leaves it unaltered since esc_attr() does not double-encode.
220
		 *
221
		 * This means we end up with an attribute like
222
		 * `data-gallery="{&quot;foo&quot;:&quot;&quot;&quot;}"`,
223
		 * which is interpreted by the browser as `{"foo":"""}`,
224
		 * which cannot be JSON decoded.
225
		 *
226
		 * The preferred workaround is to include the JSON_HEX_AMP (and friends)
227
		 * options, but these are not available until 5.3.0.
228
		 * Alternatively, we can use _wp_specialchars( , , , true ) instead of
229
		 * esc_attr(), which will double-encode.
230
		 *
231
		 * Since we can't rely on JSON_HEX_AMP, we do both.
232
		 *
233
		 * @todo Update when minimum is PHP 5.3+
234
		 */
235
		$gallery_attributes = _wp_specialchars( wp_check_invalid_utf8( $gallery ), ENT_QUOTES, false, true );
236
237
		$output .= sprintf(
238
			'<div id="%s" class="slideshow-window jetpack-slideshow slideshow-%s" data-trans="%s" data-autostart="%s" data-gallery="%s" itemscope itemtype="https://schema.org/ImageGallery"></div>',
239
			esc_attr( $attr['selector'] . '-slideshow' ),
240
			esc_attr( $attr['color'] ),
241
			esc_attr( $attr['trans'] ),
242
			esc_attr( $attr['autostart'] ),
243
			$gallery_attributes
244
		);
245
246
		return $output;
247
	}
248
249
	/**
250
	 * Actually enqueues the scripts and styles.
251
	 */
252
	public function enqueue_scripts() {
253
254
		wp_enqueue_script( 'jquery-cycle', plugins_url( '/js/jquery.cycle.min.js', __FILE__ ), array( 'jquery' ), '20161231', true );
255
		wp_enqueue_script(
256
			'jetpack-slideshow',
257
			Assets::get_file_url_for_environment( '_inc/build/shortcodes/js/slideshow-shortcode.min.js', 'modules/shortcodes/js/slideshow-shortcode.js' ),
258
			array( 'jquery-cycle' ),
259
			'20160119.1',
260
			true
261
		);
262
		wp_enqueue_style(
263
			'jetpack-slideshow',
264
			plugins_url( '/css/slideshow-shortcode.css', __FILE__ ),
265
			array(),
266
			JETPACK__VERSION
267
		);
268
		wp_style_add_data( 'jetpack-slideshow', 'rtl', 'replace' );
269
270
		wp_localize_script(
271
			'jetpack-slideshow',
272
			'jetpackSlideshowSettings',
273
			/**
274
			 * Filters the slideshow JavaScript spinner.
275
			 *
276
			 * @module shortcodes
277
			 *
278
			 * @since 2.1.0
279
			 * @since 4.7.0 Added the `speed` option to the array of options.
280
			 *
281
			 * @param array $args
282
			 * - string - spinner        - URL of the spinner image.
283
			 * - string - speed          - Speed of the slideshow. Defaults to 4000.
284
			 * - string - label_prev     - Aria label for slideshow's previous button
285
			 * - string - label_stop    - Aria label for slideshow's pause button
286
			 * - string - label_next     - Aria label for slideshow's next button
287
			 */
288
			apply_filters(
289
				'jetpack_js_slideshow_settings',
290
				array(
291
					'spinner'    => plugins_url( '/img/slideshow-loader.gif', __FILE__ ),
292
					'speed'      => '4000',
293
					'label_prev' => __( 'Previous Slide', 'jetpack' ),
294
					'label_stop' => __( 'Pause Slideshow', 'jetpack' ),
295
					'label_next' => __( 'Next Slide', 'jetpack' ),
296
				)
297
			)
298
		);
299
	}
300
301
	/**
302
	 * Instantiate shortcode.
303
	 */
304
	public static function init() {
305
		new Jetpack_Slideshow_Shortcode();
306
	}
307
}
308
309
Jetpack_Slideshow_Shortcode::init();
310