Completed
Push — try/woocommerce-analytics ( 2b8c13...0a25c9 )
by
unknown
32:37 queued 22:26
created

Jetpack_Lazy_Images   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 302
Duplicated Lines 5.3 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 0
Metric Value
dl 16
loc 302
rs 8.6
c 0
b 0
f 0
wmc 37
lcom 2
cbo 1

13 Methods

Rating   Name   Duplication   Size   Complexity  
A instance() 0 7 2
B __construct() 0 29 3
A setup_filters() 8 8 1
A remove_filters() 8 8 1
A allow_lazy_attributes() 0 16 2
B add_image_placeholders() 0 21 6
B should_skip_image_with_blacklisted_class() 0 29 5
A process_image() 0 20 3
B process_image_attributes() 0 58 7
A get_placeholder_image() 0 18 1
A flatten_kses_hair_data() 0 7 2
A build_attributes_string() 0 11 3
A enqueue_assets() 0 12 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
class Jetpack_Lazy_Images {
4
	private static $__instance = null;
5
6
	/**
7
	 * Singleton implementation
8
	 *
9
	 * @return object
10
	 */
11
	public static function instance() {
12
		if ( is_null( self::$__instance ) ) {
13
			self::$__instance = new Jetpack_Lazy_Images();
14
		}
15
16
		return self::$__instance;
17
	}
18
19
	/**
20
	 * Registers actions
21
	 */
22
	private function __construct() {
23
		if ( is_admin() ) {
24
			return;
25
		}
26
27
		/**
28
		 * Whether the lazy-images module should load.
29
		 *
30
		 * This filter is not prefixed with jetpack_ to provide a smoother migration
31
		 * process from the WordPress Lazy Load plugin.
32
		 *
33
		 * @module lazy-images
34
		 *
35
		 * @since 5.6.0
36
		 *
37
		 * @param bool true Whether lazy image loading should occur.
38
		 */
39
		if ( ! apply_filters( 'lazyload_is_enabled', true ) ) {
40
			return;
41
		}
42
43
		add_action( 'wp_head', array( $this, 'setup_filters' ), 9999 ); // we don't really want to modify anything in <head> since it's mostly all metadata
44
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
45
46
		// Do not lazy load avatar in admin bar
47
		add_action( 'admin_bar_menu', array( $this, 'remove_filters' ), 0 );
48
49
		add_filter( 'wp_kses_allowed_html', array( $this, 'allow_lazy_attributes' ) );
50
	}
51
52 View Code Duplication
	public function setup_filters() {
53
		add_filter( 'the_content', array( $this, 'add_image_placeholders' ), PHP_INT_MAX ); // run this later, so other content filters have run, including image_add_wh on WP.com
54
		add_filter( 'post_thumbnail_html', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
55
		add_filter( 'get_avatar', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
56
		add_filter( 'widget_text', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
57
		add_filter( 'get_image_tag', array( $this, 'add_image_placeholders' ), PHP_INT_MAX);
58
		add_filter( 'wp_get_attachment_image_attributes', array( __CLASS__, 'process_image_attributes' ), PHP_INT_MAX );
59
	}
60
61 View Code Duplication
	public function remove_filters() {
62
		remove_filter( 'the_content', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
63
		remove_filter( 'post_thumbnail_html', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
64
		remove_filter( 'get_avatar', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
65
		remove_filter( 'widget_text', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
66
		remove_filter( 'get_image_tag', array( $this, 'add_image_placeholders' ), PHP_INT_MAX);
67
		remove_filter( 'wp_get_attachment_image_attributes', array( __CLASS__, 'process_image_attributes' ), PHP_INT_MAX );
68
	}
69
70
	/**
71
	 * Ensure that our lazy image attributes are not filtered out of image tags.
72
	 *
73
	 * @param array $allowed_tags The allowed tags and their attributes.
74
	 * @return array
75
	 */
76
	public function allow_lazy_attributes( $allowed_tags ) {
77
		if ( ! isset( $allowed_tags['img'] ) ) {
78
			return $allowed_tags;
79
		}
80
81
		// But, if images are allowed, ensure that our attributes are allowed!
82
		$img_attributes = array_merge( $allowed_tags['img'], array(
83
			'data-lazy-src' => 1,
84
			'data-lazy-srcset' => 1,
85
			'data-lazy-sizes' => 1,
86
		) );
87
88
		$allowed_tags['img'] = $img_attributes;
89
90
		return $allowed_tags;
91
	}
92
93
	public function add_image_placeholders( $content ) {
94
		// Don't lazyload for feeds, previews
95
		if ( is_feed() || is_preview() ) {
96
			return $content;
97
		}
98
99
		// Don't lazy-load if the content has already been run through previously
100
		if ( false !== strpos( $content, 'data-lazy-src' ) ) {
101
			return $content;
102
		}
103
104
		// Don't lazyload for amp-wp content
105
		if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
106
			return $content;
107
		}
108
109
		// This is a pretty simple regex, but it works
110
		$content = preg_replace_callback( '#<(img)([^>]+?)(>(.*?)</\\1>|[\/]?>)#si', array( __CLASS__, 'process_image' ), $content );
111
112
		return $content;
113
	}
114
115
	/**
116
	 * Returns true when a given string of classes contains a class signifying lazy images
117
	 * should not process the image.
118
	 *
119
	 * @since 5.9.0
120
	 *
121
	 * @param string $classes A string of space-separated classes.
122
	 * @return bool
123
	 */
124
	public static function should_skip_image_with_blacklisted_class( $classes ) {
125
		$blacklisted_classes = array(
126
			'skip-lazy',
127
			'gazette-featured-content-thumbnail',
128
		);
129
130
		/**
131
		 * Allow plugins and themes to tell lazy images to skip an image with a given class.
132
		 *
133
		 * @module lazy-images
134
		 *
135
		 * @since 5.9.0
136
		 *
137
		 * @param array An array of strings where each string is a class.
138
		 */
139
		$blacklisted_classes = apply_filters( 'jetpack_lazy_images_blacklisted_classes', $blacklisted_classes );
140
141
		if ( ! is_array( $blacklisted_classes ) || empty( $blacklisted_classes ) ) {
142
			return false;
143
		}
144
145
		foreach ( $blacklisted_classes as $class ) {
146
			if ( false !== strpos( $classes, $class ) ) {
147
				return true;
148
			}
149
		}
150
151
		return false;
152
	}
153
154
	/**
155
	 * Processes images in content by acting as the preg_replace_callback
156
	 *
157
	 * @since 5.6.0
158
	 *
159
	 * @param array $matches
160
	 *
161
	 * @return string The image with updated lazy attributes
162
	 */
163
	static function process_image( $matches ) {
164
		$old_attributes_str = $matches[2];
165
		$old_attributes_kses_hair = wp_kses_hair( $old_attributes_str, wp_allowed_protocols() );
166
167
		if ( empty( $old_attributes_kses_hair['src'] ) ) {
168
			return $matches[0];
169
		}
170
171
		$old_attributes = self::flatten_kses_hair_data( $old_attributes_kses_hair );
172
		$new_attributes = self::process_image_attributes( $old_attributes );
173
174
		// If we didn't add lazy attributes, just return the original image source.
175
		if ( empty( $new_attributes['data-lazy-src'] ) ) {
176
			return $matches[0];
177
		}
178
179
		$new_attributes_str = self::build_attributes_string( $new_attributes );
180
181
		return sprintf( '<img %1$s><noscript>%2$s</noscript>', $new_attributes_str, $matches[0] );
182
	}
183
184
	/**
185
	 * Given an array of image attributes, updates the `src`, `srcset`, and `sizes` attributes so
186
	 * that they load lazily.
187
	 *
188
	 * @since 5.7.0
189
	 *
190
	 * @param array $attributes
191
	 *
192
	 * @return array The updated image attributes array with lazy load attributes
193
	 */
194
	static function process_image_attributes( $attributes ) {
195
		if ( empty( $attributes['src'] ) ) {
196
			return $attributes;
197
		}
198
199
		if ( ! empty( $attributes['class'] ) && self::should_skip_image_with_blacklisted_class( $attributes['class'] ) ) {
200
			return $attributes;
201
		}
202
203
		/**
204
		 * Allow plugins and themes to conditionally skip processing an image via its attributes.
205
		 *
206
		 * @module-lazy-images
207
		 *
208
		 * @since 5.9.0
209
		 *
210
		 * @param bool  Default to not skip processing the current image.
211
		 * @param array An array of attributes via wp_kses_hair() for the current image.
212
		 */
213
		if ( apply_filters( 'jetpack_lazy_images_skip_image_with_atttributes', false, $attributes ) ) {
214
			return $attributes;
215
		}
216
217
		$old_attributes = $attributes;
218
219
		// Set placeholder and lazy-src
220
		$attributes['src'] = self::get_placeholder_image();
221
		$attributes['data-lazy-src'] = $old_attributes['src'];
222
223
		// Handle `srcset`
224
		if ( ! empty( $attributes['srcset'] ) ) {
225
			$attributes['data-lazy-srcset'] = $old_attributes['srcset'];
226
			unset( $attributes['srcset'] );
227
		}
228
229
		// Handle `sizes`
230
		if ( ! empty( $attributes['sizes'] ) ) {
231
			$attributes['data-lazy-sizes'] = $old_attributes['sizes'];
232
			unset( $attributes['sizes'] );
233
		}
234
235
		/**
236
		 * Allow plugins and themes to override the attributes on the image before the content is updated.
237
		 *
238
		 * One potential use of this filter is for themes that set `height:auto` on the `img` tag.
239
		 * With this filter, the theme could get the width and height attributes from the
240
		 * $attributes array and then add a style tag that sets those values as well, which could
241
		 * minimize reflow as images load.
242
		 *
243
		 * @module lazy-images
244
		 *
245
		 * @since 5.6.0
246
		 *
247
		 * @param array An array containing the attributes for the image, where the key is the attribute name
248
		 *              and the value is the attribute value.
249
		 */
250
		return apply_filters( 'jetpack_lazy_images_new_attributes', $attributes );
251
	}
252
253
	private static function get_placeholder_image() {
254
		/**
255
		 * Allows plugins and themes to modify the placeholder image.
256
		 *
257
		 * This filter is not prefixed with jetpack_ to provide a smoother migration
258
		 * process from the WordPress Lazy Load plugin.
259
		 *
260
		 * @module lazy-images
261
		 *
262
		 * @since 5.6.0
263
		 *
264
		 * @param string The URL to the placeholder image
265
		 */
266
		return apply_filters(
267
			'lazyload_images_placeholder_image',
268
			plugins_url( 'modules/lazy-images/images/1x1.trans.gif', JETPACK__PLUGIN_FILE )
269
		);
270
	}
271
272
	private static function flatten_kses_hair_data( $attributes ) {
273
		$flattened_attributes = array();
274
		foreach ( $attributes as $name => $attribute ) {
275
			$flattened_attributes[ $name ] = $attribute['value'];
276
		}
277
		return $flattened_attributes;
278
	}
279
280
	private static function build_attributes_string( $attributes ) {
281
		$string = array();
282
		foreach ( $attributes as $name => $value ) {
283
			if ( '' === $value ) {
284
				$string[] = sprintf( '%s', $name );
285
			} else {
286
				$string[] = sprintf( '%s="%s"', $name, esc_attr( $value ) );
287
			}
288
		}
289
		return implode( ' ', $string );
290
	}
291
292
	public function enqueue_assets() {
293
		wp_enqueue_script(
294
			'jetpack-lazy-images',
295
			Jetpack::get_file_url_for_environment(
296
				'_inc/build/lazy-images/js/lazy-images.min.js',
297
				'modules/lazy-images/js/lazy-images.js'
298
			),
299
			array( 'jquery' ),
300
			JETPACK__VERSION,
301
			true
302
		);
303
	}
304
}
305