Completed
Push — fix/7357 ( 13a0c4...764bff )
by
unknown
11:52
created

Jetpack_Lazy_Images   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 210
Duplicated Lines 5.71 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 0
Metric Value
dl 12
loc 210
rs 10
c 0
b 0
f 0
wmc 26
lcom 2
cbo 1

11 Methods

Rating   Name   Duplication   Size   Complexity  
A instance() 0 7 2
B __construct() 0 27 3
A setup_filters() 6 6 1
A remove_filters() 6 6 1
B add_image_placeholders() 0 21 6
A process_image() 0 14 2
B process_image_attributes() 0 40 4
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
50 View Code Duplication
	public function setup_filters() {
51
		add_filter( 'the_content', array( $this, 'add_image_placeholders' ), 99 ); // run this later, so other content filters have run, including image_add_wh on WP.com
52
		add_filter( 'post_thumbnail_html', array( $this, 'add_image_placeholders' ), 11 );
53
		add_filter( 'get_avatar', array( $this, 'add_image_placeholders' ), 11 );
54
		add_filter( 'wp_get_attachment_image_attributes', array( __CLASS__, 'process_image_attributes' ), PHP_INT_MAX );
55
	}
56
57 View Code Duplication
	public function remove_filters() {
58
		remove_filter( 'the_content', array( $this, 'add_image_placeholders' ), 99 );
59
		remove_filter( 'post_thumbnail_html', array( $this, 'add_image_placeholders' ), 11 );
60
		remove_filter( 'get_avatar', array( $this, 'add_image_placeholders' ), 11 );
61
		remove_filter( 'wp_get_attachment_image_attributes', array( __CLASS__, 'process_image_attributes' ), PHP_INT_MAX );
62
	}
63
64
	public function add_image_placeholders( $content ) {
65
		// Don't lazyload for feeds, previews
66
		if ( is_feed() || is_preview() ) {
67
			return $content;
68
		}
69
70
		// Don't lazy-load if the content has already been run through previously
71
		if ( false !== strpos( $content, 'data-lazy-src' ) ) {
72
			return $content;
73
		}
74
75
		// Don't lazyload for amp-wp content
76
		if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
77
			return $content;
78
		}
79
80
		// This is a pretty simple regex, but it works
81
		$content = preg_replace_callback( '#<(img)([^>]+?)(>(.*?)</\\1>|[\/]?>)#si', array( __CLASS__, 'process_image' ), $content );
82
83
		return $content;
84
	}
85
86
	/**
87
	 * Processes images in content by acting as the preg_replace_callback
88
	 *
89
	 * @since 5.6.0
90
	 *
91
	 * @param array $matches
92
	 *
93
	 * @return string The image with updated lazy attributes
94
	 */
95
	static function process_image( $matches ) {
96
		$old_attributes_str = $matches[2];
97
		$old_attributes_kses_hair = wp_kses_hair( $old_attributes_str, wp_allowed_protocols() );
98
99
		if ( empty( $old_attributes_kses_hair['src'] ) ) {
100
			return $matches[0];
101
		}
102
103
		$old_attributes = self::flatten_kses_hair_data( $old_attributes_kses_hair );
104
		$new_attributes = self::process_image_attributes( $old_attributes );
105
		$new_attributes_str = self::build_attributes_string( $new_attributes );
106
107
		return sprintf( '<img %1$s><noscript>%2$s</noscript>', $new_attributes_str, $matches[0] );
108
	}
109
110
	/**
111
	 * Given an array of image attributes, updates the `src`, `srcset`, and `sizes` attributes so
112
	 * that they load lazily.
113
	 *
114
	 * @since 5.7.0
115
	 *
116
	 * @param array $attributes
117
	 *
118
	 * @return array The updated image attributes array with lazy load attributes
119
	 */
120
	static function process_image_attributes( $attributes ) {
121
		if ( empty( $attributes['src'] ) ) {
122
			return $attributes;
123
		}
124
125
		$old_attributes = $attributes;
126
127
		// Set placeholder and lazy-src
128
		$attributes['src'] = self::get_placeholder_image();
129
		$attributes['data-lazy-src'] = $old_attributes['src'];
130
131
		// Handle `srcset`
132
		if ( ! empty( $attributes['srcset'] ) ) {
133
			$attributes['data-lazy-srcset'] = $old_attributes['srcset'];
134
			unset( $attributes['srcset'] );
135
		}
136
137
		// Handle `sizes`
138
		if ( ! empty( $attributes['sizes'] ) ) {
139
			$attributes['data-lazy-sizes'] = $old_attributes['sizes'];
140
			unset( $attributes['sizes'] );
141
		}
142
143
		/**
144
		 * Allow plugins and themes to override the attributes on the image before the content is updated.
145
		 *
146
		 * One potential use of this filter is for themes that set `height:auto` on the `img` tag.
147
		 * With this filter, the theme could get the width and height attributes from the
148
		 * $attributes array and then add a style tag that sets those values as well, which could
149
		 * minimize reflow as images load.
150
		 *
151
		 * @module lazy-images
152
		 *
153
		 * @since 5.6.0
154
		 *
155
		 * @param array An array containing the attributes for the image, where the key is the attribute name
156
		 *              and the value is the attribute value.
157
		 */
158
		return apply_filters( 'jetpack_lazy_images_new_attributes', $attributes );
159
	}
160
161
	private static function get_placeholder_image() {
162
		/**
163
		 * Allows plugins and themes to modify the placeholder image.
164
		 *
165
		 * This filter is not prefixed with jetpack_ to provide a smoother migration
166
		 * process from the WordPress Lazy Load plugin.
167
		 *
168
		 * @module lazy-images
169
		 *
170
		 * @since 5.6.0
171
		 *
172
		 * @param string The URL to the placeholder image
173
		 */
174
		return apply_filters(
175
			'lazyload_images_placeholder_image',
176
			plugins_url( 'modules/lazy-images/images/1x1.trans.gif', JETPACK__PLUGIN_FILE )
177
		);
178
	}
179
180
	private static function flatten_kses_hair_data( $attributes ) {
181
		$flattened_attributes = array();
182
		foreach ( $attributes as $name => $attribute ) {
183
			$flattened_attributes[ $name ] = $attribute['value'];
184
		}
185
		return $flattened_attributes;
186
	}
187
188
	private static function build_attributes_string( $attributes ) {
189
		$string = array();
190
		foreach ( $attributes as $name => $value ) {
191
			if ( '' === $value ) {
192
				$string[] = sprintf( '%s', $name );
193
			} else {
194
				$string[] = sprintf( '%s="%s"', $name, esc_attr( $value ) );
195
			}
196
		}
197
		return implode( ' ', $string );
198
	}
199
200
	public function enqueue_assets() {
201
		wp_enqueue_script(
202
			'jetpack-lazy-images',
203
			Jetpack::get_file_url_for_environment(
204
				'_inc/build/lazy-images/js/lazy-images.min.js',
205
				'modules/lazy-images/js/lazy-images.js'
206
			),
207
			array( 'jquery' ),
208
			JETPACK__VERSION,
209
			true
210
		);
211
	}
212
}
213