Gallery   F
last analyzed

Complexity

Total Complexity 79

Size/Duplication

Total Lines 491
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 52.38%

Importance

Changes 0
Metric Value
wmc 79
lcom 1
cbo 7
dl 0
loc 491
ccs 88
cts 168
cp 0.5238
rs 2.08
c 0
b 0
f 0

12 Methods

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

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
			$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 1
		return [ $html, 'nowiki' => true, 'isHTML' => true ];
184
	}
185
186
	/**
187
	 * Handles queries where the images (and optionally their captions) are specified as properties.
188
	 *
189
	 * @since 1.5.3
190
	 *
191
	 * @param SMWQueryResult $results
192
	 * @param TraditionalImageGallery $ig
193
	 * @param string $imageProperty
194
	 * @param string $captionProperty
195
	 * @param string $redirectProperty
196
	 * @param $outputMode
197
	 */
198
	protected function addImageProperties( SMWQueryResult $results, &$ig, $imageProperty, $captionProperty, $redirectProperty, $outputMode ) {
199
		while ( /* array of SMWResultArray */
200
		$rows = $results->getNext() ) { // Objects (pages)
201
			$images = [];
202
			$captions = [];
203
			$redirects = [];
204
205
			for ( $i = 0, $n = count( $rows ); $i < $n; $i++ ) { // Properties
206
				/**
207
				 * @var \SMWResultArray $resultArray
208
				 * @var \SMWDataValue $dataValue
209
				 */
210
				$resultArray = $rows[$i];
211
212
				$label = $resultArray->getPrintRequest()->getMode() == SMWPrintRequest::PRINT_THIS
213
					? '-' : $resultArray->getPrintRequest()->getLabel();
214
215
				// Make sure always use real label here otherwise it results in an empty array
216
				if ( $resultArray->getPrintRequest()->getLabel() == $imageProperty ) {
217
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
218
						if ( $dataValue->getTypeID() == '_wpg' ) {
219
							$images[] = $dataValue->getDataItem()->getTitle();
0 ignored issues
show
Bug introduced by Stephan
It seems like you code against a specific sub-type and not the parent class SMWDataItem as the method getTitle() does only exist in the following sub-classes of SMWDataItem: SMWDIWikiPage, SMW\DIWikiPage. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
220
						}
221
					}
222
				} elseif ( $label == $captionProperty ) {
223
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
224
						$captions[] = $dataValue->getShortText( $outputMode, $this->getLinker( true ) );
225
					}
226
				} elseif ( $label == $redirectProperty ) {
227
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
228
						if ( $dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_WIKIPAGE ) {
229
							$redirects[] = $dataValue->getTitle();
230
						} elseif ( $dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_URI ) {
231
							$redirects[] = $dataValue->getURL();
232
						}
233
					}
234
				}
235
			}
236
237
			// Check available matches against captions
238
			$amountMatches = count( $captions ) == count( $images );
239
			$hasCaption = $amountMatches || count( $captions ) > 0;
240
241
			// Check available matches against redirects
242
			$amountRedirects = count( $redirects ) == count( $images );
243
			$hasRedirect = $amountRedirects || count( $redirects ) > 0;
244
245
			/**
246
			 * @var Title $imgTitle
247
			 */
248
			foreach ( $images as $imgTitle ) {
249
				if ( $imgTitle->exists() ) {
250
					$imgCaption = $hasCaption ? ( $amountMatches ? array_shift( $captions ) : $captions[0] ) : '';
251
					$imgRedirect = $hasRedirect ? ( $amountRedirects ? array_shift( $redirects ) : $redirects[0] ) : '';
252
					$this->addImageToGallery( $ig, $imgTitle, $imgCaption, $imgRedirect );
253
				}
254
			}
255
		}
256
	}
257
258
	/**
259
	 * Handles queries where the result objects are image pages.
260
	 *
261
	 * @since 1.5.3
262
	 *
263
	 * @param SMWQueryResult $results
264
	 * @param TraditionalImageGallery $ig
265
	 */
266 1
	protected function addImagePages( SMWQueryResult $results, &$ig ) {
267 1
		while ( $row = $results->getNext() ) {
268
			/**
269
			 * @var \SMWResultArray $firstField
270
			 */
271 1
			$firstField = $row[0];
272 1
273
			/** @var \SMWDataValue $nextObject */
274 1
			$nextObject = $firstField->getNextDataValue();
275 1
276
			if ( $nextObject !== false ) {
277
				$dataItem = $nextObject->getDataItem();
278 1
				$imgTitle = method_exists( $dataItem, 'getTitle' ) ? $dataItem->getTitle() : null;
279 1
280
				// Ensure the title belongs to the image namespace
281
				if ( $imgTitle instanceof Title && $imgTitle->getNamespace() === NS_FILE ) {
0 ignored issues
show
Bug introduced by mwjames
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...
282 1
					$imgCaption = '';
283 1
284 1
					// Is there a property queried for display with ?property
285 1
					if ( isset( $row[1] ) ) {
286
						$imgCaption = $row[1]->getNextDataValue();
287
						if ( is_object( $imgCaption ) ) {
288
							$imgCaption = $imgCaption->getShortText( $this->outputMode, $this->getLinker( true ) );
289 1
						}
290
					}
291
292
					$this->addImageToGallery( $ig, $imgTitle, $imgCaption );
293 1
				}
294
			}
295
		}
296
	}
297
298
	/**
299
	 * Adds a single image to the gallery.
300
	 * Takes care of automatically adding a caption when none is provided and parsing it's wikitext.
301
	 *
302
	 * @since 1.5.3
303
	 *
304
	 * @param TraditionalImageGallery $ig The gallery to add the image to
305
	 * @param Title $imgTitle The title object of the page of the image
306 1
	 * @param string $imgCaption An optional caption for the image
307
	 * @param string $imgRedirect
308 1
	 */
309
	protected function addImageToGallery( &$ig, Title $imgTitle, $imgCaption, $imgRedirect = '' ) {
310
311
		if ( empty( $imgCaption ) ) {
312
			if ( $this->params['autocaptions'] ) {
313
				$imgCaption = $imgTitle->getBaseText();
314
315
				if ( !$this->params['fileextensions'] ) {
316
					$imgCaption = preg_replace( '#\.[^.]+$#', '', $imgCaption );
317
				}
318
			} else {
319 1
				$imgCaption = '';
320 1
			}
321
		} else {
322
			if ( $imgTitle instanceof Title && $imgTitle->getNamespace() == NS_FILE && !$this->isSpecialPage() ) {
0 ignored issues
show
Bug introduced by mwjames
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...
323
				$imgCaption = $ig->mParser->recursiveTagParse( $imgCaption );
324 1
			}
325 1
		}
326 1
		// Use image alt as helper for either text
327
		$imgAlt = $this->params['redirects'] === '' ? $imgCaption : $imgRedirect !== '' ? $imgRedirect : '';
328
		$ig->add( $imgTitle, $imgCaption, $imgAlt );
329
	}
330
331
	/**
332
	 * Returns the overlay setting
333
	 *
334
	 * @since 1.8
335 1
	 *
336 1
	 * @return string
337
	 */
338
	private function getImageOverlay() {
339
		if ( array_key_exists( 'overlay', $this->params ) && $this->params['overlay'] == true ) {
340 1
			SMWOutputs::requireResource( 'ext.srf.gallery.overlay' );
341
			return ' srf-overlay';
342
		} else {
343
			return '';
344
		}
345
	}
346
347
	/**
348
	 * Init carousel widget
349
	 *
350
	 * @since 1.8
351
	 *
352
	 * @return string[]
353
	 */
354
	private function getCarouselWidget() {
355
356
		// Set attributes for jcarousel
357
		$dataAttribs = [
358
			'wrap' => 'both', // Whether to wrap at the first/last item (or both) and jump back to the start/end.
359
			'vertical' => 'false', // Orientation: vertical = false means horizontal
360
			'rtl' => 'false', // Directionality: rtl = false means ltr
361
		];
362
363
		// Use the perrow parameter to determine the scroll sequence.
364
		if ( empty( $this->params['perrow'] ) ) {
365
			$dataAttribs['scroll'] = 1;  // default 1
366
		} else {
367
			$dataAttribs['scroll'] = $this->params['perrow'];
368
			$dataAttribs['visible'] = $this->params['perrow'];
369
		}
370
371
		$attribs = [
372
			'id' => uniqid(),
373
			'class' => 'jcarousel jcarousel-skin-smw' . $this->getImageOverlay(),
374
			'style' => 'display:none;',
375
		];
376
377
		foreach ( $dataAttribs as $name => $value ) {
378
			$attribs['data-' . $name] = $value;
379
		}
380
381
		SMWOutputs::requireResource( 'ext.srf.gallery.carousel' );
382
383
		return $attribs;
384
	}
385
386
	/**
387
	 * Init slideshow widget
388
	 *
389
	 * @since 1.8
390
	 *
391
	 * @return string[]
392
	 */
393
	private function getSlideshowWidget() {
394
395
		$attribs = [
396
			'id' => uniqid(),
397
			'class' => $this->getImageOverlay(),
398
			'style' => 'display:none;',
399
			'data-nav-control' => $this->params['navigation']
400
		];
401
402
		SMWOutputs::requireResource( 'ext.srf.gallery.slideshow' );
403
404
		return $attribs;
405
	}
406
407
	/**
408
	 * @see SMWResultPrinter::getParamDefinitions
409
	 *
410
	 * @since 1.8
411
	 *
412
	 * @param $definitions array of IParamDefinition
413 1
	 *
414 1
	 * @return array of IParamDefinition|array
415
	 */
416 1
	public function getParamDefinitions( array $definitions ) {
417
		$params = parent::getParamDefinitions( $definitions );
418
419
		$params['class'] = [
420
			'type' => 'string',
421
			'message' => 'srf-paramdesc-class',
422 1
			'default' => ''
423
		];
424
425
		$params['widget'] = [
426
			'type' => 'string',
427
			'default' => '',
428
			'message' => 'srf-paramdesc-widget',
429 1
			'values' => [ 'carousel', 'slideshow', '' ]
430
		];
431
432
		$params['navigation'] = [
433
			'type' => 'string',
434
			'default' => 'nav',
435
			'message' => 'srf-paramdesc-navigation',
436 1
			'values' => [ 'nav', 'pager', 'auto' ]
437
		];
438
439
		$params['overlay'] = [
440
			'type' => 'boolean',
441
			'default' => false,
442 1
			'message' => 'srf-paramdesc-overlay'
443
		];
444
445
		$params['perrow'] = [
446
			'type' => 'integer',
447
			'default' => '',
448 1
			'message' => 'srf_paramdesc_perrow'
449
		];
450
451
		$params['widths'] = [
452
			'type' => 'integer',
453
			'default' => '',
454 1
			'message' => 'srf_paramdesc_widths'
455
		];
456
457
		$params['heights'] = [
458
			'type' => 'integer',
459
			'default' => '',
460 1
			'message' => 'srf_paramdesc_heights'
461
		];
462
463
		$params['autocaptions'] = [
464
			'type' => 'boolean',
465
			'default' => true,
466 1
			'message' => 'srf_paramdesc_autocaptions'
467
		];
468
469
		$params['fileextensions'] = [
470
			'type' => 'boolean',
471
			'default' => false,
472 1
			'message' => 'srf_paramdesc_fileextensions'
473
		];
474
475
		$params['captionproperty'] = [
476
			'type' => 'string',
477
			'default' => '',
478 1
			'message' => 'srf_paramdesc_captionproperty'
479
		];
480
481
		$params['imageproperty'] = [
482
			'type' => 'string',
483
			'default' => '',
484 1
			'message' => 'srf_paramdesc_imageproperty'
485
		];
486
487
		$params['redirects'] = [
488
			'type' => 'string',
489
			'default' => '',
490 1
			'message' => 'srf-paramdesc-redirects'
491
		];
492
493
		return $params;
494
	}
495
496 1
	/**
497 1
	 * @return bool
498 1
	 */
499
	private function isSpecialPage() {
500
		$title = $GLOBALS['wgTitle'];
501
		return $title instanceof Title && $title->isSpecialPage();
0 ignored issues
show
Bug introduced by mwjames
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...
502
	}
503
504 1
	/**
505 1
	 * @return bool|null|string
506 1
	 */
507
	private function getFileNsTextForPageLanguage() {
508
		$title = $GLOBALS['wgTitle'];
509
		return $title instanceof Title ? $title->getPageLanguage()->getNsText( NS_FILE ) : null;
0 ignored issues
show
Bug introduced by mwjames
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...
510
	}
511
512
}
513