Completed
Push — master ( 777c00...f61c3d )
by GIT
05:00
created

Gallery::getResultText()   F

Complexity

Conditions 26
Paths > 20000

Size

Total Lines 126

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 53
CRAP Score 26.104

Importance

Changes 0
Metric Value
dl 0
loc 126
ccs 53
cts 56
cp 0.9464
rs 0
c 0
b 0
f 0
cc 26
nc 294912
nop 2
crap 26.104

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 1
	public function getName() {
30 1
		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 4
	protected function buildResult( SMWQueryResult $results ) {
43
44
		// Intro/outro are not planned to work with the widget option
45 4
		if ( ( $this->params['intro'] !== '' || $this->params['outro'] !== '' ) && $this->params['widget'] !== '' ) {
46 1
			$results->addErrors(
47
				[
48 1
					$this->msg( 'srf-error-option-mix', 'widget' )->inContentLanguage()->text()
49
				]
50
			);
51
52 1
			return '';
53
		};
54
55 3
		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 3
	public function getResultText( SMWQueryResult $results, $outputmode ) {
67
68 3
		$ig = new TraditionalImageGallery();
69
70 3
		$ig->setShowBytes( false );
71 3
		$ig->setShowFilename( false );
72
73 3
		if ( method_exists( $ig, 'setShowDimensions' ) ) {
74 3
			$ig->setShowDimensions( false );
75
		}
76
77 3
		$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 3
		if ( !$this->isSpecialPage() ) {
82 3
			$ig->setParser( $GLOBALS['wgParser'] );
83
		}
84
85 3
		$html = '';
86 3
		$processing = '';
87
88 3
		if ( $this->params['widget'] == 'carousel' ) {
89
			// Carousel widget
90 1
			$ig->setAttributes( $this->getCarouselWidget() );
91 3
		} elseif ( $this->params['widget'] == 'slideshow' ) {
92
			// Slideshow widget
93 1
			$ig->setAttributes( $this->getSlideshowWidget() );
94
		} else {
95
96
			// Standard gallery attributes
97
			$attribs = [
98 3
				'id' => uniqid(),
99 3
				'class' => $this->getImageOverlay(),
100
			];
101
102 3
			$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 3
		if ( $this->params['redirects'] !== '' && !$this->params['overlay'] ) {
108 1
			SMWOutputs::requireResource( 'ext.srf.gallery.redirect' );
109
		}
110
111
		// For the carousel widget, the perrow option should not be set
112 3
		if ( $this->params['perrow'] !== '' && $this->params['widget'] !== 'carousel' ) {
113
			$ig->setPerRow( $this->params['perrow'] );
114
		}
115
116 3
		if ( $this->params['widths'] !== '' ) {
117 1
			$ig->setWidths( $this->params['widths'] );
118
		}
119
120 3
		if ( $this->params['heights'] !== '' ) {
121 1
			$ig->setHeights( $this->params['heights'] );
122
		}
123
124 3
		$printReqLabels = [];
125 3
		$redirectType = '';
126
127
		/**
128
		 * @var SMWPrintRequest $printReq
129
		 */
130 3
		foreach ( $results->getPrintRequests() as $printReq ) {
131 3
			$printReqLabels[] = $printReq->getLabel();
132
133
			// Get redirect type
134 3
			if ( $this->params['redirects'] === $printReq->getLabel() ) {
135 3
				$redirectType = $printReq->getTypeID();
136
			}
137
		}
138
139 3
		if ( $this->params['imageproperty'] !== '' && in_array( $this->params['imageproperty'], $printReqLabels ) ||
140 3
			$this->params['redirects'] !== '' && in_array( $this->params['redirects'], $printReqLabels ) ) {
141
142 1
			$this->addImageProperties(
143 1
				$results,
144
				$ig,
145 1
				$this->params['imageproperty'],
146 1
				$this->params['captionproperty'],
147 1
				$this->params['redirects'],
148
				$outputmode
149
			);
150
		} else {
151 3
			$this->addImagePages( $results, $ig );
152
		}
153
154
		// SRF Global settings
155 3
		SRFUtils::addGlobalJSVariables();
156
157
		// Display a processing image as long as the DOM is no ready
158 3
		if ( $this->params['widget'] !== '' ) {
159 1
			$processing = SRFUtils::htmlProcessingElement();
160
		}
161
162
		// Beautify the class selector
163 3
		$class = $this->params['widget'] ? '-' . $this->params['widget'] . ' ' : '';
164 3
		$class = $this->params['redirects'] !== '' && $this->params['overlay'] === false ? $class . ' srf-redirect' . ' ' : $class;
165 3
		$class = $this->params['class'] ? $class . ' ' . $this->params['class'] : $class;
166
167
		// Separate content from result output
168 3
		if ( !$ig->isEmpty() ) {
169
			$attribs = [
170 3
				'class' => 'srf-gallery' . $class,
171 3
				'data-redirect-type' => $redirectType,
172 3
				'data-ns-text' => $this->getFileNsTextForPageLanguage()
173
			];
174
175 3
			$html = Html::rawElement( 'div', $attribs, $processing . $ig->toHTML() );
176
		}
177
178
		// If available, create a link that points to further results
179 3
		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 3
		if ( $results == '' && $this->params[ 'default' ] !== '' ) {
186
			$html = $this->params[ 'default' ];
187
		}
188
189
190 3
		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 1
	protected function addImageProperties( SMWQueryResult $results, &$ig, $imageProperty, $captionProperty, $redirectProperty, $outputMode ) {
206
		while ( /* array of SMWResultArray */
207 1
		$rows = $results->getNext() ) { // Objects (pages)
208 1
			$images = [];
209 1
			$captions = [];
210 1
			$redirects = [];
211
212 1
			for ( $i = 0, $n = count( $rows ); $i < $n; $i++ ) { // Properties
213
				/**
214
				 * @var \SMWResultArray $resultArray
215
				 * @var \SMWDataValue $dataValue
216
				 */
217 1
				$resultArray = $rows[$i];
218
219 1
				$label = $resultArray->getPrintRequest()->getMode() == SMWPrintRequest::PRINT_THIS
220 1
					? '-' : $resultArray->getPrintRequest()->getLabel();
221
222
				// Make sure always use real label here otherwise it results in an empty array
223 1
				if ( $resultArray->getPrintRequest()->getLabel() == $imageProperty ) {
224 1
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
225 1
						if ( $dataValue->getTypeID() == '_wpg' ) {
226 1
							$images[] = $dataValue->getDataItem()->getTitle();
227
						}
228
					}
229 1
				} elseif ( $label == $captionProperty ) {
230
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
231
						$captions[] = $dataValue->getShortText( $outputMode, $this->getLinker( true ) );
232
					}
233 1
				} elseif ( $label == $redirectProperty ) {
234 1
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
235 1
						if ( $dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_WIKIPAGE ) {
236 1
							$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 1
			$amountMatches = count( $captions ) == count( $images );
246 1
			$hasCaption = $amountMatches || count( $captions ) > 0;
247
248
			// Check available matches against redirects
249 1
			$amountRedirects = count( $redirects ) == count( $images );
250 1
			$hasRedirect = $amountRedirects || count( $redirects ) > 0;
251
252
			/**
253
			 * @var Title $imgTitle
254
			 */
255 1
			foreach ( $images as $imgTitle ) {
256 1
				if ( $imgTitle->exists() ) {
257 1
					$imgCaption = $hasCaption ? ( $amountMatches ? array_shift( $captions ) : $captions[0] ) : '';
258 1
					$imgRedirect = $hasRedirect ? ( $amountRedirects ? array_shift( $redirects ) : $redirects[0] ) : '';
259 1
					$this->addImageToGallery( $ig, $imgTitle, $imgCaption, $imgRedirect );
260
				}
261
			}
262
		}
263 1
	}
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 3
	protected function addImagePages( SMWQueryResult $results, &$ig ) {
274 3
		while ( $row = $results->getNext() ) {
275
			/**
276
			 * @var \SMWResultArray $firstField
277
			 */
278 3
			$firstField = $row[0];
279
280
			/** @var \SMWDataValue $nextObject */
281 3
			$nextObject = $firstField->getNextDataValue();
282
283 3
			if ( $nextObject !== false ) {
284 3
				$dataItem = $nextObject->getDataItem();
285 3
				$imgTitle = method_exists( $dataItem, 'getTitle' ) ? $dataItem->getTitle() : null;
286
287
				// Ensure the title belongs to the image namespace
288 3
				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 3
					$imgCaption = '';
290
291
					// Is there a property queried for display with ?property
292 3
					if ( isset( $row[1] ) ) {
293 3
						$imgCaption = $row[1]->getNextDataValue();
294 3
						if ( is_object( $imgCaption ) ) {
295 3
							$imgCaption = $imgCaption->getShortText( $this->outputMode, $this->getLinker( true ) );
296
						}
297
					}
298
299 3
					$this->addImageToGallery( $ig, $imgTitle, $imgCaption );
300
				}
301
			}
302
		}
303 3
	}
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 3
	protected function addImageToGallery( &$ig, Title $imgTitle, $imgCaption, $imgRedirect = '' ) {
317
318 3
		if ( empty( $imgCaption ) ) {
319 1
			if ( $this->params['autocaptions'] ) {
320 1
				$imgCaption = $imgTitle->getBaseText();
321
322 1
				if ( !$this->params['fileextensions'] ) {
323 1
					$imgCaption = preg_replace( '#\.[^.]+$#', '', $imgCaption );
324
				}
325
			} else {
326 1
				$imgCaption = '';
327
			}
328
		} else {
329 3
			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 3
				$imgCaption = $ig->mParser->recursiveTagParse( $imgCaption );
331
			}
332
		}
333
334 3
		if ( $this->params['captiontemplate'] !== '' ) {
335 1
			$templateCode = "{{" . $this->params['captiontemplate'] .
336 1
				"|imageraw=".$imgTitle->getPrefixedText()."|imagecaption=$imgCaption|imageredirect=$imgRedirect}}";
337
338 1
			$imgCaption = $ig->mParser->recursiveTagParse( $templateCode );
339
340
		}
341
342
		// Use image alt as helper for either text
343 3
		$imgAlt = $this->params['redirects'] === '' ? $imgCaption : ( $imgRedirect !== '' ? $imgRedirect : '' );
344 3
		$ig->add( $imgTitle, $imgCaption, $imgAlt );
345 3
	}
346
347
	/**
348
	 * Returns the overlay setting
349
	 *
350
	 * @since 1.8
351
	 *
352
	 * @return string
353
	 */
354 3
	private function getImageOverlay() {
355 3
		if ( array_key_exists( 'overlay', $this->params ) && $this->params['overlay'] == true ) {
356 1
			SMWOutputs::requireResource( 'ext.srf.gallery.overlay' );
357 1
			return ' srf-overlay';
358
		} else {
359 3
			return '';
360
		}
361
	}
362
363
	/**
364
	 * Init carousel widget
365
	 *
366
	 * @since 1.8
367
	 *
368
	 * @return string[]
369
	 */
370 1
	private function getCarouselWidget() {
371
372
		// Set attributes for jcarousel
373
		$dataAttribs = [
374 1
			'wrap' => 'both', // Whether to wrap at the first/last item (or both) and jump back to the start/end.
375
			'vertical' => 'false', // Orientation: vertical = false means horizontal
376
			'rtl' => 'false', // Directionality: rtl = false means ltr
377
		];
378
379
		// Use the perrow parameter to determine the scroll sequence.
380 1
		if ( empty( $this->params['perrow'] ) ) {
381 1
			$dataAttribs['scroll'] = 1;  // default 1
382
		} else {
383
			$dataAttribs['scroll'] = $this->params['perrow'];
384
			$dataAttribs['visible'] = $this->params['perrow'];
385
		}
386
387
		$attribs = [
388 1
			'id' => uniqid(),
389 1
			'class' => 'jcarousel jcarousel-skin-smw' . $this->getImageOverlay(),
390 1
			'style' => 'display:none;',
391
		];
392
393 1
		foreach ( $dataAttribs as $name => $value ) {
394 1
			$attribs['data-' . $name] = $value;
395
		}
396
397 1
		SMWOutputs::requireResource( 'ext.srf.gallery.carousel' );
398
399 1
		return $attribs;
400
	}
401
402
	/**
403
	 * Init slideshow widget
404
	 *
405
	 * @since 1.8
406
	 *
407
	 * @return string[]
408
	 */
409 1
	private function getSlideshowWidget() {
410
411
		$attribs = [
412 1
			'id' => uniqid(),
413 1
			'class' => $this->getImageOverlay(),
414 1
			'style' => 'display:none;',
415 1
			'data-nav-control' => $this->params['navigation']
416
		];
417
418 1
		SMWOutputs::requireResource( 'ext.srf.gallery.slideshow' );
419
420 1
		return $attribs;
421
	}
422
423
	/**
424
	 * @see SMWResultPrinter::getParamDefinitions
425
	 *
426
	 * @since 1.8
427
	 *
428
	 * @param $definitions array of IParamDefinition
429
	 *
430
	 * @return array of IParamDefinition|array
431
	 */
432 3
	public function getParamDefinitions( array $definitions ) {
433 3
		$params = parent::getParamDefinitions( $definitions );
434
435 3
		$params['class'] = [
436
			'type' => 'string',
437
			'message' => 'srf-paramdesc-class',
438
			'default' => ''
439
		];
440
441 3
		$params['widget'] = [
442
			'type' => 'string',
443
			'default' => '',
444
			'message' => 'srf-paramdesc-widget',
445
			'values' => [ 'carousel', 'slideshow', '' ]
446
		];
447
448 3
		$params['navigation'] = [
449
			'type' => 'string',
450
			'default' => 'nav',
451
			'message' => 'srf-paramdesc-navigation',
452
			'values' => [ 'nav', 'pager', 'auto' ]
453
		];
454
455 3
		$params['overlay'] = [
456
			'type' => 'boolean',
457
			'default' => false,
458
			'message' => 'srf-paramdesc-overlay'
459
		];
460
461 3
		$params['perrow'] = [
462
			'type' => 'integer',
463
			'default' => '',
464
			'message' => 'srf_paramdesc_perrow'
465
		];
466
467 3
		$params['widths'] = [
468
			'type' => 'integer',
469
			'default' => '',
470
			'message' => 'srf_paramdesc_widths'
471
		];
472
473 3
		$params['heights'] = [
474
			'type' => 'integer',
475
			'default' => '',
476
			'message' => 'srf_paramdesc_heights'
477
		];
478
479 3
		$params['autocaptions'] = [
480
			'type' => 'boolean',
481
			'default' => true,
482
			'message' => 'srf_paramdesc_autocaptions'
483
		];
484
485 3
		$params['fileextensions'] = [
486
			'type' => 'boolean',
487
			'default' => false,
488
			'message' => 'srf_paramdesc_fileextensions'
489
		];
490
491 3
		$params['captionproperty'] = [
492
			'type' => 'string',
493
			'default' => '',
494
			'message' => 'srf_paramdesc_captionproperty'
495
		];
496
497 3
		$params['captiontemplate'] = [
498
			'type' => 'string',
499
			'default' => '',
500
			'message' => 'srf-paramdesc-captiontemplate'
501
		];
502
503 3
		$params['imageproperty'] = [
504
			'type' => 'string',
505
			'default' => '',
506
			'message' => 'srf_paramdesc_imageproperty'
507
		];
508
509 3
		$params['redirects'] = [
510
			'type' => 'string',
511
			'default' => '',
512
			'message' => 'srf-paramdesc-redirects'
513
		];
514
515 3
		return $params;
516
	}
517
518
	/**
519
	 * @return bool
520
	 */
521 3
	private function isSpecialPage() {
522 3
		$title = $GLOBALS['wgTitle'];
523 3
		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...
524
	}
525
526
	/**
527
	 * @return bool|null|string
528
	 */
529 3
	private function getFileNsTextForPageLanguage() {
530 3
		$title = $GLOBALS['wgTitle'];
531 3
		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...
532
	}
533
534
}
535