Completed
Push — master ( e4957f...670487 )
by
unknown
07:52
created

Gallery   F

Complexity

Total Complexity 81

Size/Duplication

Total Lines 498
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 53.85%

Importance

Changes 0
Metric Value
wmc 81
lcom 1
cbo 3
dl 0
loc 498
ccs 91
cts 169
cp 0.5385
rs 2
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getName() 0 3 1
A buildResult() 0 15 4
B getParamDefinitions() 0 79 1
A isSpecialPage() 0 4 2
F getResultText() 0 126 26
F addImageProperties() 0 59 21
B addImagePages() 0 31 8
B addImageToGallery() 0 21 9
A getImageOverlay() 0 8 3
A getCarouselWidget() 0 31 3
A getSlideshowWidget() 0 13 1
A getFileNsTextForPageLanguage() 0 4 2

How to fix   Complexity   

Complex Class

Complex classes like Gallery often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Gallery, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace SRF;
4
5
use Html;
6
use SMW\ResultPrinter;
7
use SMWDataItem;
8
use SMWOutputs;
9
use SMWPrintRequest;
10
use SMWQueryResult;
11
use SRFUtils;
12
use Title;
13
use TraditionalImageGallery;
14
15
/**
16
 * Result printer that outputs query results as a image gallery.
17
 *
18
 * @author Jeroen De Dauw < [email protected] >
19
 * @author mwjames
20
 * @author Rowan Rodrik van der Molen
21
 */
22
class Gallery extends ResultPrinter {
23
24
	/**
25
	 * @see SMWResultPrinter::getName
26
	 *
27
	 * @return string
28
	 */
29
	public function getName() {
30
		return $this->msg( 'srf_printername_gallery' )->text();
31
	}
32
33
	/**
34
	 * @see SMWResultPrinter::buildResult
35
	 *
36
	 * @since 1.8
37
	 *
38
	 * @param SMWQueryResult $results
39
	 *
40
	 * @return string
41
	 */
42 1
	protected function buildResult( SMWQueryResult $results ) {
43
44
		// Intro/outro are not planned to work with the widget option
45 1
		if ( ( $this->params['intro'] !== '' || $this->params['outro'] !== '' ) && $this->params['widget'] !== '' ) {
46
			$results->addErrors(
47
				[
48
					$this->msg( 'srf-error-option-mix', 'widget' )->inContentLanguage()->text()
49
				]
50
			);
51
52
			return '';
53
		};
54
55 1
		return $this->getResultText( $results, $this->outputMode );
56
	}
57
58
	/**
59
	 * @see SMWResultPrinter::getResultText
60
	 *
61
	 * @param $results SMWQueryResult
62
	 * @param $outputmode integer
63
	 *
64
	 * @return string | array
65
	 */
66 1
	public function getResultText( SMWQueryResult $results, $outputmode ) {
67
68 1
		$ig = new TraditionalImageGallery();
69
70 1
		$ig->setShowBytes( false );
71 1
		$ig->setShowFilename( false );
72
73 1
		if ( method_exists( $ig, 'setShowDimensions' ) ) {
74 1
			$ig->setShowDimensions( false );
75
		}
76
77 1
		$ig->setCaption( $this->mIntro ); // set caption to IQ header
78
79
		// No need for a special page to use the parser but for the "normal" page
80
		// view we have to ensure caption text is parsed correctly through the parser
81 1
		if ( !$this->isSpecialPage() ) {
82 1
			$ig->setParser( $GLOBALS['wgParser'] );
83
		}
84
85 1
		$html = '';
86 1
		$processing = '';
87
88 1
		if ( $this->params['widget'] == 'carousel' ) {
89
			// Carousel widget
90
			$ig->setAttributes( $this->getCarouselWidget() );
91 1
		} elseif ( $this->params['widget'] == 'slideshow' ) {
92
			// Slideshow widget
93
			$ig->setAttributes( $this->getSlideshowWidget() );
94
		} else {
95
96
			// Standard gallery attributes
97
			$attribs = [
98 1
				'id' => uniqid(),
99 1
				'class' => $this->getImageOverlay(),
100
			];
101
102 1
			$ig->setAttributes( $attribs );
103
		}
104
105
		// Only use redirects where the overlay option is not used and redirect
106
		// thumb images towards a different target
107 1
		if ( $this->params['redirects'] !== '' && !$this->params['overlay'] ) {
108
			SMWOutputs::requireResource( 'ext.srf.gallery.redirect' );
109
		}
110
111
		// For the carousel widget, the perrow option should not be set
112 1
		if ( $this->params['perrow'] !== '' && $this->params['widget'] !== 'carousel' ) {
113
			$ig->setPerRow( $this->params['perrow'] );
114
		}
115
116 1
		if ( $this->params['widths'] !== '' ) {
117
			$ig->setWidths( $this->params['widths'] );
118
		}
119
120 1
		if ( $this->params['heights'] !== '' ) {
121
			$ig->setHeights( $this->params['heights'] );
122
		}
123
124 1
		$printReqLabels = [];
125 1
		$redirectType = '';
126
127
		/**
128
		 * @var SMWPrintRequest $printReq
129
		 */
130 1
		foreach ( $results->getPrintRequests() as $printReq ) {
131 1
			$printReqLabels[] = $printReq->getLabel();
132
133
			// Get redirect type
134 1
			if ( $this->params['redirects'] === $printReq->getLabel() ) {
135 1
				$redirectType = $printReq->getTypeID();
136
			}
137
		}
138
139 1
		if ( $this->params['imageproperty'] !== '' && in_array( $this->params['imageproperty'], $printReqLabels ) ||
140 1
			$this->params['redirects'] !== '' && in_array( $this->params['redirects'], $printReqLabels ) ) {
141
142
			$this->addImageProperties(
143
				$results,
144
				$ig,
145
				$this->params['imageproperty'],
146
				$this->params['captionproperty'],
147
				$this->params['redirects'],
148
				$outputmode
149
			);
150
		} else {
151 1
			$this->addImagePages( $results, $ig );
152
		}
153
154
		// SRF Global settings
155 1
		SRFUtils::addGlobalJSVariables();
156
157
		// Display a processing image as long as the DOM is no ready
158 1
		if ( $this->params['widget'] !== '' ) {
159
			$processing = SRFUtils::htmlProcessingElement();
160
		}
161
162
		// Beautify the class selector
163 1
		$class = $this->params['widget'] ? '-' . $this->params['widget'] . ' ' : '';
164 1
		$class = $this->params['redirects'] !== '' && $this->params['overlay'] === false ? $class . ' srf-redirect' . ' ' : $class;
165 1
		$class = $this->params['class'] ? $class . ' ' . $this->params['class'] : $class;
166
167
		// Separate content from result output
168 1
		if ( !$ig->isEmpty() ) {
169
			$attribs = [
170 1
				'class' => 'srf-gallery' . $class,
171 1
				'data-redirect-type' => $redirectType,
172 1
				'data-ns-text' => $this->getFileNsTextForPageLanguage()
173
			];
174
175 1
			$html = Html::rawElement( 'div', $attribs, $processing . $ig->toHTML() );
176
		}
177
178
		// If available, create a link that points to further results
179 1
		if ( $this->linkFurtherResults( $results ) ) {
180
			$html .= $this->getLink( $results, SMW_OUTPUT_HTML )->getText( SMW_OUTPUT_HTML, $this->mLinker );
181
		}
182
183
		// If available and no results, return default message
184
185 1
		if ( $results == '' && $this->params[ 'default' ] !== '' ) {
186
			$html = $this->params[ 'default' ];
187
		}
188
189
190 1
		return [ $html, 'nowiki' => true, 'isHTML' => true ];
191
	}
192
193
	/**
194
	 * Handles queries where the images (and optionally their captions) are specified as properties.
195
	 *
196
	 * @since 1.5.3
197
	 *
198
	 * @param SMWQueryResult $results
199
	 * @param TraditionalImageGallery $ig
200
	 * @param string $imageProperty
201
	 * @param string $captionProperty
202
	 * @param string $redirectProperty
203
	 * @param $outputMode
204
	 */
205
	protected function addImageProperties( SMWQueryResult $results, &$ig, $imageProperty, $captionProperty, $redirectProperty, $outputMode ) {
206
		while ( /* array of SMWResultArray */
207
		$rows = $results->getNext() ) { // Objects (pages)
208
			$images = [];
209
			$captions = [];
210
			$redirects = [];
211
212
			for ( $i = 0, $n = count( $rows ); $i < $n; $i++ ) { // Properties
213
				/**
214
				 * @var \SMWResultArray $resultArray
215
				 * @var \SMWDataValue $dataValue
216
				 */
217
				$resultArray = $rows[$i];
218
219
				$label = $resultArray->getPrintRequest()->getMode() == SMWPrintRequest::PRINT_THIS
220
					? '-' : $resultArray->getPrintRequest()->getLabel();
221
222
				// Make sure always use real label here otherwise it results in an empty array
223
				if ( $resultArray->getPrintRequest()->getLabel() == $imageProperty ) {
224
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
225
						if ( $dataValue->getTypeID() == '_wpg' ) {
226
							$images[] = $dataValue->getDataItem()->getTitle();
227
						}
228
					}
229
				} elseif ( $label == $captionProperty ) {
230
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
231
						$captions[] = $dataValue->getShortText( $outputMode, $this->getLinker( true ) );
232
					}
233
				} elseif ( $label == $redirectProperty ) {
234
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
235
						if ( $dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_WIKIPAGE ) {
236
							$redirects[] = $dataValue->getTitle();
237
						} elseif ( $dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_URI ) {
238
							$redirects[] = $dataValue->getURL();
239
						}
240
					}
241
				}
242
			}
243
244
			// Check available matches against captions
245
			$amountMatches = count( $captions ) == count( $images );
246
			$hasCaption = $amountMatches || count( $captions ) > 0;
247
248
			// Check available matches against redirects
249
			$amountRedirects = count( $redirects ) == count( $images );
250
			$hasRedirect = $amountRedirects || count( $redirects ) > 0;
251
252
			/**
253
			 * @var Title $imgTitle
254
			 */
255
			foreach ( $images as $imgTitle ) {
256
				if ( $imgTitle->exists() ) {
257
					$imgCaption = $hasCaption ? ( $amountMatches ? array_shift( $captions ) : $captions[0] ) : '';
258
					$imgRedirect = $hasRedirect ? ( $amountRedirects ? array_shift( $redirects ) : $redirects[0] ) : '';
259
					$this->addImageToGallery( $ig, $imgTitle, $imgCaption, $imgRedirect );
260
				}
261
			}
262
		}
263
	}
264
265
	/**
266
	 * Handles queries where the result objects are image pages.
267
	 *
268
	 * @since 1.5.3
269
	 *
270
	 * @param SMWQueryResult $results
271
	 * @param TraditionalImageGallery $ig
272
	 */
273 1
	protected function addImagePages( SMWQueryResult $results, &$ig ) {
274 1
		while ( $row = $results->getNext() ) {
275
			/**
276
			 * @var \SMWResultArray $firstField
277
			 */
278 1
			$firstField = $row[0];
279
280
			/** @var \SMWDataValue $nextObject */
281 1
			$nextObject = $firstField->getNextDataValue();
282
283 1
			if ( $nextObject !== false ) {
284 1
				$dataItem = $nextObject->getDataItem();
285 1
				$imgTitle = method_exists( $dataItem, 'getTitle' ) ? $dataItem->getTitle() : null;
286
287
				// Ensure the title belongs to the image namespace
288 1
				if ( $imgTitle instanceof Title && $imgTitle->getNamespace() === NS_FILE ) {
0 ignored issues
show
Bug introduced by
The class Title does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
289 1
					$imgCaption = '';
290
291
					// Is there a property queried for display with ?property
292 1
					if ( isset( $row[1] ) ) {
293 1
						$imgCaption = $row[1]->getNextDataValue();
294 1
						if ( is_object( $imgCaption ) ) {
295 1
							$imgCaption = $imgCaption->getShortText( $this->outputMode, $this->getLinker( true ) );
296
						}
297
					}
298
299 1
					$this->addImageToGallery( $ig, $imgTitle, $imgCaption );
300
				}
301
			}
302
		}
303 1
	}
304
305
	/**
306
	 * Adds a single image to the gallery.
307
	 * Takes care of automatically adding a caption when none is provided and parsing it's wikitext.
308
	 *
309
	 * @since 1.5.3
310
	 *
311
	 * @param TraditionalImageGallery $ig The gallery to add the image to
312
	 * @param Title $imgTitle The title object of the page of the image
313
	 * @param string $imgCaption An optional caption for the image
314
	 * @param string $imgRedirect
315
	 */
316 1
	protected function addImageToGallery( &$ig, Title $imgTitle, $imgCaption, $imgRedirect = '' ) {
317
318 1
		if ( empty( $imgCaption ) ) {
319
			if ( $this->params['autocaptions'] ) {
320
				$imgCaption = $imgTitle->getBaseText();
321
322
				if ( !$this->params['fileextensions'] ) {
323
					$imgCaption = preg_replace( '#\.[^.]+$#', '', $imgCaption );
324
				}
325
			} else {
326
				$imgCaption = '';
327
			}
328
		} else {
329 1
			if ( $imgTitle instanceof Title && $imgTitle->getNamespace() == NS_FILE && !$this->isSpecialPage() ) {
0 ignored issues
show
Bug introduced by
The class Title does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
330 1
				$imgCaption = $ig->mParser->recursiveTagParse( $imgCaption );
331
			}
332
		}
333
		// Use image alt as helper for either text
334 1
		$imgAlt = $this->params['redirects'] === '' ? $imgCaption : ( $imgRedirect !== '' ? $imgRedirect : '' );
335 1
		$ig->add( $imgTitle, $imgCaption, $imgAlt );
336 1
	}
337
338
	/**
339
	 * Returns the overlay setting
340
	 *
341
	 * @since 1.8
342
	 *
343
	 * @return string
344
	 */
345 1
	private function getImageOverlay() {
346 1
		if ( array_key_exists( 'overlay', $this->params ) && $this->params['overlay'] == true ) {
347
			SMWOutputs::requireResource( 'ext.srf.gallery.overlay' );
348
			return ' srf-overlay';
349
		} else {
350 1
			return '';
351
		}
352
	}
353
354
	/**
355
	 * Init carousel widget
356
	 *
357
	 * @since 1.8
358
	 *
359
	 * @return string[]
360
	 */
361
	private function getCarouselWidget() {
362
363
		// Set attributes for jcarousel
364
		$dataAttribs = [
365
			'wrap' => 'both', // Whether to wrap at the first/last item (or both) and jump back to the start/end.
366
			'vertical' => 'false', // Orientation: vertical = false means horizontal
367
			'rtl' => 'false', // Directionality: rtl = false means ltr
368
		];
369
370
		// Use the perrow parameter to determine the scroll sequence.
371
		if ( empty( $this->params['perrow'] ) ) {
372
			$dataAttribs['scroll'] = 1;  // default 1
373
		} else {
374
			$dataAttribs['scroll'] = $this->params['perrow'];
375
			$dataAttribs['visible'] = $this->params['perrow'];
376
		}
377
378
		$attribs = [
379
			'id' => uniqid(),
380
			'class' => 'jcarousel jcarousel-skin-smw' . $this->getImageOverlay(),
381
			'style' => 'display:none;',
382
		];
383
384
		foreach ( $dataAttribs as $name => $value ) {
385
			$attribs['data-' . $name] = $value;
386
		}
387
388
		SMWOutputs::requireResource( 'ext.srf.gallery.carousel' );
389
390
		return $attribs;
391
	}
392
393
	/**
394
	 * Init slideshow widget
395
	 *
396
	 * @since 1.8
397
	 *
398
	 * @return string[]
399
	 */
400
	private function getSlideshowWidget() {
401
402
		$attribs = [
403
			'id' => uniqid(),
404
			'class' => $this->getImageOverlay(),
405
			'style' => 'display:none;',
406
			'data-nav-control' => $this->params['navigation']
407
		];
408
409
		SMWOutputs::requireResource( 'ext.srf.gallery.slideshow' );
410
411
		return $attribs;
412
	}
413
414
	/**
415
	 * @see SMWResultPrinter::getParamDefinitions
416
	 *
417
	 * @since 1.8
418
	 *
419
	 * @param $definitions array of IParamDefinition
420
	 *
421
	 * @return array of IParamDefinition|array
422
	 */
423 1
	public function getParamDefinitions( array $definitions ) {
424 1
		$params = parent::getParamDefinitions( $definitions );
425
426 1
		$params['class'] = [
427
			'type' => 'string',
428
			'message' => 'srf-paramdesc-class',
429
			'default' => ''
430
		];
431
432 1
		$params['widget'] = [
433
			'type' => 'string',
434
			'default' => '',
435
			'message' => 'srf-paramdesc-widget',
436
			'values' => [ 'carousel', 'slideshow', '' ]
437
		];
438
439 1
		$params['navigation'] = [
440
			'type' => 'string',
441
			'default' => 'nav',
442
			'message' => 'srf-paramdesc-navigation',
443
			'values' => [ 'nav', 'pager', 'auto' ]
444
		];
445
446 1
		$params['overlay'] = [
447
			'type' => 'boolean',
448
			'default' => false,
449
			'message' => 'srf-paramdesc-overlay'
450
		];
451
452 1
		$params['perrow'] = [
453
			'type' => 'integer',
454
			'default' => '',
455
			'message' => 'srf_paramdesc_perrow'
456
		];
457
458 1
		$params['widths'] = [
459
			'type' => 'integer',
460
			'default' => '',
461
			'message' => 'srf_paramdesc_widths'
462
		];
463
464 1
		$params['heights'] = [
465
			'type' => 'integer',
466
			'default' => '',
467
			'message' => 'srf_paramdesc_heights'
468
		];
469
470 1
		$params['autocaptions'] = [
471
			'type' => 'boolean',
472
			'default' => true,
473
			'message' => 'srf_paramdesc_autocaptions'
474
		];
475
476 1
		$params['fileextensions'] = [
477
			'type' => 'boolean',
478
			'default' => false,
479
			'message' => 'srf_paramdesc_fileextensions'
480
		];
481
482 1
		$params['captionproperty'] = [
483
			'type' => 'string',
484
			'default' => '',
485
			'message' => 'srf_paramdesc_captionproperty'
486
		];
487
488 1
		$params['imageproperty'] = [
489
			'type' => 'string',
490
			'default' => '',
491
			'message' => 'srf_paramdesc_imageproperty'
492
		];
493
494 1
		$params['redirects'] = [
495
			'type' => 'string',
496
			'default' => '',
497
			'message' => 'srf-paramdesc-redirects'
498
		];
499
500 1
		return $params;
501
	}
502
503
	/**
504
	 * @return bool
505
	 */
506 1
	private function isSpecialPage() {
507 1
		$title = $GLOBALS['wgTitle'];
508 1
		return $title instanceof Title && $title->isSpecialPage();
0 ignored issues
show
Bug introduced by
The class Title does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
509
	}
510
511
	/**
512
	 * @return bool|null|string
513
	 */
514 1
	private function getFileNsTextForPageLanguage() {
515 1
		$title = $GLOBALS['wgTitle'];
516 1
		return $title instanceof Title ? $title->getPageLanguage()->getNsText( NS_FILE ) : null;
0 ignored issues
show
Bug introduced by
The class Title does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
517
	}
518
519
}
520