Completed
Push — develop ( d494ed...7721c5 )
by Paul
02:24
created

Gallery::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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