Completed
Push — develop ( 13bd87...d494ed )
by Paul
02:08
created

Gallery   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 269
Duplicated Lines 2.6 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 35
lcom 1
cbo 4
dl 7
loc 269
rs 9
c 0
b 0
f 0

17 Methods

Rating   Name   Duplication   Size   Complexity  
A query() 0 14 1
A render() 0 7 1
A renderImage() 0 18 2
A renderPagination() 0 12 2
A __construct() 7 7 1
A getBoolValue() 0 9 2
A getGalleryArg() 0 11 4
A getImagesPerPageArg() 0 11 4
A getLazyloadArg() 0 4 1
A getMediaArg() 0 14 3
A getPaged() 0 4 3
A getPaginationArg() 0 4 1
A getPermalinksArg() 0 4 1
A getPhotoswipeData() 0 11 1
A getValue() 0 7 3
A normalizeArgs() 0 22 2
A renderImageTag() 0 16 3

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
namespace GeminiLabs\Castor;
4
5
use GeminiLabs\Castor\Helpers\PostMeta;
6
use GeminiLabs\Castor\Helpers\Theme;
7
use GeminiLabs\Castor\Helpers\Utility;
8
use GeminiLabs\Castor\Image;
9
use WP_Post;
10
use WP_Query;
11
12
class Gallery
13
{
14
	public $image;
15
	public $postmeta;
16
	public $theme;
17
	public $utility;
18
19
	protected $args;
20
21 View Code Duplication
	public function __construct( Image $image, PostMeta $postmeta, Theme $theme, Utility $utility )
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
22
	{
23
		$this->image    = $image;
24
		$this->postmeta = $postmeta;
25
		$this->theme    = $theme;
26
		$this->utility  = $utility;
27
	}
28
29
	/**
30
	 * @return WP_Query
31
	 */
32
	public function query( array $args = [] )
33
	{
34
		$this->normalizeArgs( $args );
35
36
		return new WP_Query([
37
			'orderby'        => 'post__in',
38
			'paged'          => $this->getPaged(),
39
			'post__in'       => $this->args['media'],
40
			'post_mime_type' => 'image',
41
			'post_type'      => 'attachment',
42
			'post_status'    => 'inherit',
43
			'posts_per_page' => $this->args['images_per_page'],
44
		]);
45
	}
46
47
	/**
48
	 * @return string
49
	 */
50
	public function render( WP_Query $gallery )
51
	{
52
		$images = array_reduce( $gallery->posts, function( $images, $attachment ) {
53
			return $images . $this->renderImage( $attachment );
54
		});
55
		return sprintf( '<div class="gallery-images" itemscope itemtype="http://schema.org/ImageGallery">%s</div>', $images );
56
	}
57
58
	/**
59
	 * @return null|string
60
	 */
61
	public function renderImage( WP_Post $attachment )
62
	{
63
		$image = $this->image->get( $attachment->ID );
64
		if( !$image )return;
65
		return sprintf(
66
			'<figure class="gallery-image" data-w="%s" data-h="%s" data-ps=\'%s\' itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">' .
67
				'%s<figcaption itemprop="caption description">' .
68
					'%s <span itemprop="copyrightHolder">%s</span>' .
69
				'</figcaption>' .
70
			'</figure>',
71
			$image->thumbnail['width'],
72
			$image->thumbnail['height'],
73
			$this->getPhotoswipeData( $image ),
74
			$this->renderImageTag( $image ),
75
			$image->caption,
76
			$image->copyright
77
		);
78
	}
79
80
	/**
81
	 * @return null|string
82
	 */
83
	public function renderPagination( WP_Query $query )
84
	{
85
		if( !$this->args['pagination'] )return;
86
		return paginate_links([
87
			'before_page_number' => '<span class="screen-reader-text">' . __( 'Page', 'castor' ) . ' </span>',
88
			'current'            => $query->query['paged'],
89
			'mid_size'           => 1,
90
			'next_text'          => __( 'Next', 'castor' ),
91
			'prev_text'          => __( 'Previous', 'castor' ),
92
			'total'              => $query->max_num_pages,
93
		]);
94
	}
95
96
	/**
97
	 * @param string $key
98
	 * @param mixed  $value
99
	 *
100
	 * @return bool
101
	 */
102
	protected function getBoolValue( $key, $value = null )
103
	{
104
		$bool = $this->getValue( $key, $value );
105
106
		if( is_null( filter_var( $bool, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE ))) {
107
			$bool = $this->postmeta->get( $bool );
108
		}
109
		return wp_validate_boolean( $bool );
110
	}
111
112
	/**
113
	 * @param mixed $value
114
	 *
115
	 * @return int
116
	 */
117
	protected function getGalleryArg( $value = null )
118
	{
119
		$gallery = $this->getValue( 'gallery', $value );
120
121
		if( !is_numeric( $gallery ) && is_string( $gallery )) {
122
			$gallery = intval( $this->postmeta->get( $gallery ));
123
		}
124
		return !is_null( get_post( $gallery ))
125
			? intval( $gallery )
126
			: 0;
127
	}
128
129
	/**
130
	 * @param mixed $value
131
	 *
132
	 * @return int
133
	 */
134
	protected function getImagesPerPageArg( $value = null )
135
	{
136
		$perPage = $this->getValue( 'images_per_page', $value );
137
138
		if( !is_numeric( $perPage ) && is_string( $perPage )) {
139
			$perPage = $this->postmeta->get( $perPage );
140
		}
141
		return !!intval( $perPage )
142
			? $perPage
143
			: -1;
144
	}
145
146
	/**
147
	 * @param mixed $value
148
	 *
149
	 * @return bool
150
	 */
151
	protected function getLazyloadArg( $value = null )
152
	{
153
		return $this->getBoolValue( 'lazyload', $value );
154
	}
155
156
	/**
157
	 * @param mixed $value
158
	 *
159
	 * @return array
160
	 */
161
	protected function getMediaArg( $value = null )
162
	{
163
		$media = $this->getValue( 'media', $value );
164
165
		if( is_string( $media )) {
166
			$media = $this->postmeta->get( $media, [
167
				'ID'     => $this->getGalleryArg(),
168
				'single' => false,
169
			]);
170
		}
171
		return is_array( $media )
172
			? wp_parse_id_list( $media )
173
			: [];
174
	}
175
176
	/**
177
	 * @return int
178
	 */
179
	protected function getPaged()
180
	{
181
		return intval( get_query_var(( is_front_page() ? 'page' : 'paged' ))) ?: 1;
182
	}
183
184
	/**
185
	 * @param mixed $value
186
	 *
187
	 * @return bool
188
	 */
189
	protected function getPaginationArg( $value = null )
190
	{
191
		return $this->getBoolValue( 'pagination', $value );
192
	}
193
194
	/**
195
	 * @param mixed $value
196
	 *
197
	 * @return bool
198
	 */
199
	protected function getPermalinksArg( $value = null )
200
	{
201
		return $this->getBoolValue( 'permalinks', $value );
202
	}
203
204
	/**
205
	 * @return string
206
	 */
207
	protected function getPhotoswipeData( $image )
208
	{
209
		return sprintf( '{"l":{"src":"%s","w":%d,"h":%d},"m":{"src":"%s","w":%d,"h":%d}}',
210
			$image->large['url'],
211
			$image->large['width'],
212
			$image->large['height'],
213
			$image->medium['url'],
214
			$image->medium['width'],
215
			$image->medium['height']
216
		);
217
	}
218
219
	/**
220
	 * @param string $key
221
	 * @param mixed  $value
222
	 *
223
	 * @return mixed
224
	 */
225
	protected function getValue( $key, $value = null )
226
	{
227
		if( is_null( $value ) && isset( $this->args[$key] )) {
228
			$value = $this->args[$key];
229
		}
230
		return $value;
231
	}
232
233
	/**
234
	 * @return array
235
	 */
236
	protected function normalizeArgs( array $args = [] )
237
	{
238
		$defaults = [
239
			'gallery',         // (string) meta_key | (int) post_id
240
			'lazyload',        // (string) meta_key | (bool)
241
			'media',           // (string) meta_key | (array) post_ids
242
			'pagination',      // (string) meta_key | (bool)
243
			'images_per_page', // (string) meta_key | (int) number
244
			'permalinks',      // (string) meta_key | (bool)
245
		];
246
247
		$this->args = shortcode_atts( array_combine( $defaults, $defaults ), $args );
248
249
		array_walk( $this->args, function( &$value, $key ) {
250
			$method = $this->utility->buildMethodName( $key . '_arg' );
251
			if( method_exists( $this, $method )) {
252
				$value = call_user_func([ $this, $method ], $value );
253
			}
254
		});
255
256
		return $this->args;
257
	}
258
259
	/**
260
	 * @param object $image
261
	 *
262
	 * @return null|string
263
	 */
264
	protected function renderImageTag( $image )
265
	{
266
		$imgSrc = $this->getLazyloadArg()
267
			? $this->theme->imageUri( 'blank.gif' )
268
			: $image->thumbnail['url'];
269
270
		$imgTag = sprintf( '<img src="%s" data-src="%s" itemprop="thumbnail" alt="%s"/>',
271
			$imgSrc,
272
			$image->thumbnail['url'],
273
			$image->alt
274
		);
275
276
		return $this->getPermalinksArg()
277
			? sprintf( '<a href="%s" itemprop="contentUrl">%s</a>', $image->permalink, $imgTag )
278
			: $imgTag;
279
	}
280
}
281