Completed
Push — master ( f043e7...f26bc0 )
by mw
13s
created

SMWSpecialBrowse::execute()   C

Complexity

Conditions 10
Paths 128

Size

Total Lines 53
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 10.2918

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 53
ccs 24
cts 28
cp 0.8571
rs 6.08
cc 10
eloc 30
nc 128
nop 1
crap 10.2918

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
use SMW\DIProperty;
4
use SMW\UrlEncoder;
5
use SMW\Localizer;
6
use SMW\SemanticData;
7
use SMW\ApplicationFactory;
8
9
/**
10
 * @ingroup SMWSpecialPage
11
 * @ingroup SpecialPage
12
 *
13
 * A factbox like view on an article, implemented by a special page.
14
 *
15
 * @author Denny Vrandecic
16
 */
17
18
/**
19
 * A factbox view on one specific article, showing all the Semantic data about it
20
 *
21
 * @ingroup SMWSpecialPage
22
 * @ingroup SpecialPage
23
 */
24
class SMWSpecialBrowse extends SpecialPage {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
25
	/// int How  many incoming values should be asked for
26
	static public $incomingvaluescount = 8;
27
	/// int  How many incoming properties should be asked for
28
	static public $incomingpropertiescount = 21;
29
	/// SMWDataValue  Topic of this page
30
	private $subject = null;
31
	/// Text to be set in the query form
32
	private $articletext = "";
33
	/// bool  To display outgoing values?
34
	private $showoutgoing = true;
35
	/// bool  To display incoming values?
36
	private $showincoming = false;
37
	/// int  At which incoming property are we currently?
38
	private $offset = 0;
39
40
	/**
41
	 * Constructor
42
	 */
43
	public function __construct() {
44
		global $smwgBrowseShowAll;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
45
		parent::__construct( 'Browse', '', true, false, 'default', true );
46
		if ( $smwgBrowseShowAll ) {
47
			self::$incomingvaluescount = 21;
48
			self::$incomingpropertiescount = - 1;
49
		}
50
	}
51
52
	/**
53
	 * Main entry point for Special Pages
54
	 *
55
	 * @param[in] $query string  Given by MediaWiki
56
	 */
57 2
	public function execute( $query ) {
58 2
		global $wgRequest, $wgOut, $smwgBrowseShowAll;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
59 2
		$this->setHeaders();
60
		// get the GET parameters
61 2
		$this->articletext = $wgRequest->getVal( 'article' );
62
63
		// @see SMWInfolink::encodeParameters
64 2
		if ( $query === null && $this->getRequest()->getCheck( 'x' ) ) {
65
			$query = $this->getRequest()->getVal( 'x' );
66
		}
67
68
		// no GET parameters? Then try the URL
69 2
		if ( is_null( $this->articletext ) ) {
70 2
			$this->articletext = UrlEncoder::decode( $query );
71
		}
72
73 2
		$this->subject = \SMW\DataValueFactory::getInstance()->newTypeIDValue( '_wpg', $this->articletext );
74 2
		$offsettext = $wgRequest->getVal( 'offset' );
75 2
		$this->offset = ( is_null( $offsettext ) ) ? 0 : intval( $offsettext );
76
77 2
		$dir = $wgRequest->getVal( 'dir' );
78
79 2
		if ( $smwgBrowseShowAll ) {
80 2
			$this->showoutgoing = true;
81 2
			$this->showincoming = true;
82
		}
83
84 2
		if ( $dir === 'both' || $dir === 'in' ) {
85
			$this->showincoming = true;
86
		}
87
88 2
		if ( $dir === 'in' ) {
89
			$this->showoutgoing = false;
90
		}
91
92 2
		if ( $dir === 'out' ) {
93
			$this->showincoming = false;
94
		}
95
96 2
		$out = $this->getOutput();
97
98 2
		$out->addModuleStyles( array(
99 2
			'mediawiki.ui',
100
			'mediawiki.ui.button',
101
			'mediawiki.ui.checkbox',
102
			'mediawiki.ui.input',
103
		) );
104
105 2
		$out->addHTML( $this->displayBrowse() );
106 2
		$this->addExternalHelpLinks();
107
108 2
		SMWOutputs::commitToOutputPage( $out ); // make sure locally collected output data is pushed to the output!
109 2
	}
110
111
	/**
112
	 * Create and output HTML including the complete factbox, based on the extracted
113
	 * parameters in the execute comment.
114
	 *
115
	 * @return string  A HTML string with the factbox
116
	 */
117 2
	private function displayBrowse() {
118 2
		global $wgContLang;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
119 2
		$html = "\n";
120 2
		$leftside = !( $wgContLang->isRTL() ); // For right to left languages, all is mirrored
121 2
		$modules = array();
122
123 2
		if ( $this->subject->isValid() ) {
124
125
			$semanticData = new SemanticData( $this->subject->getDataItem() );
0 ignored issues
show
Compatibility introduced by
$this->subject->getDataItem() of type object<SMWDataItem> is not a sub-type of object<SMW\DIWikiPage>. It seems like you assume a child class of the class SMWDataItem to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
126
			$store = ApplicationFactory::getInstance()->getStore();
127
128
			$html .= $this->displayHead();
129
130
			if ( $this->showoutgoing ) {
131
				$semanticData = $store->getSemanticData( $this->subject->getDataItem() );
132
				$html .= $this->displayData( $semanticData, $leftside );
133
				$html .= $this->displayCenter();
134
			}
135
136
			if ( $this->showincoming ) {
137
				list( $indata, $more ) = $this->getInData();
138
				global $smwgBrowseShowInverse;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
139
140
				if ( !$smwgBrowseShowInverse ) {
141
					$leftside = !$leftside;
142
				}
143
144
				$html .= $this->displayData( $indata, $leftside, true );
145
				$html .= $this->displayBottom( $more );
146
			}
147
148
			$this->articletext = $this->subject->getWikiValue();
149
150
			\Hooks::run( 'SMW::Browse::AfterDataLookupComplete', array( $store, $semanticData, &$html, &$modules ) );
151
			$this->getOutput()->addModules( $modules );
152
153
			// Add a bit space between the factbox and the query form
154
			if ( !$this->including() ) {
155
				$html .= '<div style="margin-top:15px;"></div>' ."\n";
156
			}
157
		}
158
159 2
		if ( !$this->including() ) {
160 2
			$html .= $this->queryForm();
161
		}
162
163 2
		$this->getOutput()->addHTML( $html );
164 2
	}
165
166
	/**
167
	 * Creates the HTML table displaying the data of one subject.
168
	 *
169
	 * @param[in] $data SMWSemanticData  The data to be displayed
170
	 * @param[in] $left bool  Should properties be displayed on the left side?
171
	 * @param[in] $incoming bool  Is this an incoming? Or an outgoing?
172
	 *
173
	 * @return A string containing the HTML with the factbox
174
	 */
175
	private function displayData( SMWSemanticData $data, $left = true, $incoming = false ) {
176
		// Some of the CSS classes are different for the left or the right side.
177
		// In this case, there is an "i" after the "smwb-". This is set here.
178
		$ccsPrefix = $left ? 'smwb-' : 'smwb-i';
179
180
		$html = "<table class=\"{$ccsPrefix}factbox\" cellpadding=\"0\" cellspacing=\"0\">\n";
181
182
		$diProperties = $data->getProperties();
183
		$noresult = true;
184
		foreach ( $diProperties as $key => $diProperty ) {
185
			$dvProperty = \SMW\DataValueFactory::getInstance()->newDataItemValue( $diProperty, null );
186
187
			if ( $dvProperty->isVisible() ) {
188
				$dvProperty->setCaption( $this->getPropertyLabel( $dvProperty, $incoming ) );
189
				$proptext = $dvProperty->getShortHTMLText( smwfGetLinker() ) . "\n";
190
			} elseif ( $diProperty->getKey() == '_INST' ) {
191
				$proptext = smwfGetLinker()->specialLink( 'Categories' );
192
			} elseif ( $diProperty->getKey() == '_REDI' ) {
193
				$proptext = smwfGetLinker()->specialLink( 'Listredirects', 'isredirect' );
194
			} else {
195
				continue; // skip this line
196
			}
197
198
			$head  = '<th>' . $proptext . "</th>\n";
199
200
			$body  = "<td>\n";
201
202
			$values = $data->getPropertyValues( $diProperty );
203
204
			if ( $incoming && ( count( $values ) >= self::$incomingvaluescount ) ) {
205
				$moreIncoming = true;
206
				array_pop( $values );
207
			} else {
208
				$moreIncoming = false;
209
			}
210
211
			$first = true;
212
			foreach ( $values as /* SMWDataItem */ $di ) {
0 ignored issues
show
Bug introduced by
The expression $values of type array|object<SMWDataItem> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
213
				if ( $first ) {
214
					$first = false;
215
				} else {
216
					$body .= ', ';
217
				}
218
219
				if ( $incoming ) {
220
					$dv = \SMW\DataValueFactory::getInstance()->newDataItemValue( $di, null );
221
				} else {
222
					$dv = \SMW\DataValueFactory::getInstance()->newDataItemValue( $di, $diProperty );
223
				}
224
225
				$body .= "<span class=\"{$ccsPrefix}value\">" .
226
				         $this->displayValue( $dvProperty, $dv, $incoming ) . "</span>\n";
227
			}
228
229
			// Added in 2.3
230
			// link to the remaining incoming pages
231
			if ( $moreIncoming && \Hooks::run( 'SMW::Browse::BeforeIncomingPropertyValuesFurtherLinkCreate', array( $diProperty, $this->subject->getDataItem(), &$body ) ) ) {
232
				$body .= Html::element(
233
					'a',
234
					array(
235
						'href' => SpecialPage::getSafeTitleFor( 'SearchByProperty' )->getLocalURL( array(
236
							 'property' => $dvProperty->getWikiValue(),
237
							 'value' => $this->subject->getWikiValue()
238
						) )
239
					),
240
					wfMessage( 'smw_browse_more' )->text()
241
				);
242
243
			}
244
245
			$body .= "</td>\n";
246
247
			// display row
248
			$html .= "<tr class=\"{$ccsPrefix}propvalue\">\n" .
249
					( $left ? ( $head . $body ):( $body . $head ) ) . "</tr>\n";
250
			$noresult = false;
251
		} // end foreach properties
252
253
		if ( $noresult ) {
254
			$html .= "<tr class=\"smwb-propvalue\"><th> &#160; </th><td><em>" .
255
				wfMessage( $incoming ? 'smw_browse_no_incoming':'smw_browse_no_outgoing' )->text() . "</em></td></tr>\n";
256
		}
257
		$html .= "</table>\n";
258
		return $html;
259
	}
260
261
	/**
262
	 * Displays a value, including all relevant links (browse and search by property)
263
	 *
264
	 * @param[in] $property SMWPropertyValue  The property this value is linked to the subject with
265
	 * @param[in] $value SMWDataValue  The actual value
266
	 * @param[in] $incoming bool  If this is an incoming or outgoing link
267
	 *
268
	 * @return string  HTML with the link to the article, browse, and search pages
269
	 */
270
	private function displayValue( SMWPropertyValue $property, SMWDataValue $dataValue, $incoming ) {
271
		$linker = smwfGetLinker();
272
273
		// Allow the DV formatter to access a specific language code
274
		$dataValue->setLanguageCode(
275
			Localizer::getInstance()->getUserLanguage()->getCode()
276
		);
277
278
		$html = $dataValue->getLongHTMLText( $linker );
279
280
		if ( $dataValue->getTypeID() === '_wpg' || $dataValue->getTypeID() === '__sob' ) {
281
			$html .= "&#160;" . SMWInfolink::newBrowsingLink( '+', $dataValue->getLongWikiText() )->getHTML( $linker );
282
		} elseif ( $incoming && $property->isVisible() ) {
283
			$html .= "&#160;" . SMWInfolink::newInversePropertySearchLink( '+', $dataValue->getTitle(), $property->getDataItem()->getLabel(), 'smwsearch' )->getHTML( $linker );
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMWDataValue as the method getTitle() does only exist in the following sub-classes of SMWDataValue: SMWWikiPageValue. 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...
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMWDataItem as the method getLabel() does only exist in the following sub-classes of SMWDataItem: SMWDIProperty, SMW\DIProperty. 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...
284
		} elseif ( $dataValue->getProperty() instanceof DIProperty && $dataValue->getProperty()->getKey() !== '_INST' ) {
285
			$html .= $dataValue->getInfolinkText( SMW_OUTPUT_HTML, $linker );
286
		}
287
288
		return $html;
289
	}
290
291
	/**
292
	 * Displays the subject that is currently being browsed to.
293
	 *
294
	 * @return A string containing the HTML with the subject line
295
	 */
296
	private function displayHead() {
297
		global $wgOut;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
298
299
		$wgOut->setHTMLTitle( $this->subject->getTitle() );
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMWDataValue as the method getTitle() does only exist in the following sub-classes of SMWDataValue: SMWWikiPageValue. 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...
300
		$html = "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" .
301
			"<tr class=\"smwb-title\"><td colspan=\"2\">\n" .
302
			$this->subject->getLongHTMLText( smwfGetLinker() ) . "\n" .
303
			"</td></tr>\n</table>\n";
304
305
		return $html;
306
	}
307
308
	/**
309
	 * Creates the HTML for the center bar including the links with further navigation options.
310
	 *
311
	 * @return string  HTMl with the center bar
312
	 */
313
	private function displayCenter() {
314
		return "<a name=\"smw_browse_incoming\"></a>\n" .
315
		       "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" .
316
		       "<tr class=\"smwb-center\"><td colspan=\"2\">\n" .
317
		       ( $this->showincoming ?
318
			     $this->linkHere( wfMessage( 'smw_browse_hide_incoming' )->text(), true, false, 0 ):
319
		         $this->linkHere( wfMessage( 'smw_browse_show_incoming' )->text(), true, true, $this->offset ) ) .
320
		       "&#160;\n" . "</td></tr>\n" . "</table>\n";
321
	}
322
323
	/**
324
	 * Creates the HTML for the bottom bar including the links with further navigation options.
325
	 *
326
	 * @param[in] $more bool  Are there more inproperties to be displayed?
327
	 * @return string  HTMl with the bottom bar
328
	 */
329
	private function displayBottom( $more ) {
330
		$html  = "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" .
331
		         "<tr class=\"smwb-center\"><td colspan=\"2\">\n";
332
		global $smwgBrowseShowAll;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
333
		if ( !$smwgBrowseShowAll ) {
334
			if ( ( $this->offset > 0 ) || $more ) {
335
				$offset = max( $this->offset - self::$incomingpropertiescount + 1, 0 );
336
				$html .= ( $this->offset == 0 ) ? wfMessage( 'smw_result_prev' )->text():
337
					     $this->linkHere( wfMessage( 'smw_result_prev' )->text(), $this->showoutgoing, true, $offset );
338
				$offset = $this->offset + self::$incomingpropertiescount - 1;
339
				// @todo FIXME: i18n patchwork.
340
				$html .= " &#160;&#160;&#160;  <strong>" . wfMessage( 'smw_result_results' )->text() . " " . ( $this->offset + 1 ) .
341
						 " – " . ( $offset ) . "</strong>  &#160;&#160;&#160; ";
342
				$html .= $more ? $this->linkHere( wfMessage( 'smw_result_next' )->text(), $this->showoutgoing, true, $offset ):wfMessage( 'smw_result_next' )->text();
343
			}
344
		}
345
		$html .= "&#160;\n" . "</td></tr>\n" . "</table>\n";
346
		return $html;
347
	}
348
349
	/**
350
	 * Creates the HTML for a link to this page, with some parameters set.
351
	 *
352
	 * @param[in] $text string  The anchor text for the link
353
	 * @param[in] $out bool  Should the linked to page include outgoing properties?
354
	 * @param[in] $in bool  Should the linked to page include incoming properties?
355
	 * @param[in] $offset int  What is the offset for the incoming properties?
356
	 *
357
	 * @return string  HTML with the link to this page
358
	 */
359
	private function linkHere( $text, $out, $in, $offset ) {
360
		$frag = ( $text == wfMessage( 'smw_browse_show_incoming' )->text() ) ? '#smw_browse_incoming' : '';
361
362
		return Html::element(
363
			'a',
364
			array(
365
				'href' => SpecialPage::getSafeTitleFor( 'Browse' )->getLocalURL( array(
366
					'offset' => $offset,
367
					'dir' => $out ? ( $in ? 'both' : 'out' ) : 'in',
368
					'article' => $this->subject->getLongWikiText()
369
				) ) . $frag
370
			),
371
			$text
372
		);
373
	}
374
375
	/**
376
	 * Creates a Semantic Data object with the incoming properties instead of the
377
	 * usual outproperties.
378
	 *
379
	 * @return array(SMWSemanticData, bool)  The semantic data including all inproperties, and if there are more inproperties left
0 ignored issues
show
Documentation introduced by
The doc-type array(SMWSemanticData, could not be parsed: Expected "|" or "end of type", but got "(" at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
380
	 */
381
	private function getInData() {
382
		$indata = new SMWSemanticData( $this->subject->getDataItem() );
0 ignored issues
show
Compatibility introduced by
$this->subject->getDataItem() of type object<SMWDataItem> is not a sub-type of object<SMW\DIWikiPage>. It seems like you assume a child class of the class SMWDataItem to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
383
		$options = new SMWRequestOptions();
384
		$options->sort = true;
385
		$options->limit = self::$incomingpropertiescount;
386
		if ( $this->offset > 0 ) {
387
			$options->offset = $this->offset;
388
		}
389
390
		$store = ApplicationFactory::getInstance()->getStore();
391
		$inproperties = $store->getInProperties( $this->subject->getDataItem(), $options );
392
393
		if ( count( $inproperties ) == self::$incomingpropertiescount ) {
394
			$more = true;
395
			array_pop( $inproperties ); // drop the last one
396
		} else {
397
			$more = false;
398
		}
399
400
		$valoptions = new SMWRequestOptions();
401
		$valoptions->sort = true;
402
		$valoptions->limit = self::$incomingvaluescount;
403
404
		foreach ( $inproperties as $property ) {
405
			$values = $store->getPropertySubjects( $property, $this->subject->getDataItem(), $valoptions );
406
			foreach ( $values as $value ) {
407
				$indata->addPropertyObjectValue( $property, $value );
408
			}
409
		}
410
411
		// Added in 2.3
412
		\Hooks::run( 'SMW::Browse::AfterIncomingPropertiesLookupComplete', array( $store, $indata, $valoptions ) );
413
414
		return array( $indata, $more );
415
	}
416
417
	/**
418
	 * Figures out the label of the property to be used. For outgoing ones it is just
419
	 * the text, for incoming ones we try to figure out the inverse one if needed,
420
	 * either by looking for an explicitly stated one or by creating a default one.
421
	 *
422
	 * @param[in] $property SMWPropertyValue  The property of interest
423
	 * @param[in] $incoming bool  If it is an incoming property
424
	 *
425
	 * @return string  The label of the property
426
	 */
427
	private function getPropertyLabel( SMWPropertyValue $property, $incoming = false ) {
428
		global $smwgBrowseShowInverse;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
429
430
		if ( $incoming && $smwgBrowseShowInverse ) {
431
			$oppositeprop = SMWPropertyValue::makeUserProperty( wfMessage( 'smw_inverse_label_property' )->text() );
432
			$labelarray = ApplicationFactory::getInstance()->getStore()->getPropertyValues( $property->getDataItem()->getDiWikiPage(), $oppositeprop->getDataItem() );
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMWDataItem as the method getDiWikiPage() does only exist in the following sub-classes of SMWDataItem: SMWDIProperty, SMW\DIProperty. 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...
433
			$rv = ( count( $labelarray ) > 0 ) ? $labelarray[0]->getLongWikiText():
434
				wfMessage( 'smw_inverse_label_default', $property->getWikiValue() )->text();
435
		} else {
436
			$rv = $property->getWikiValue();
437
		}
438
439
		return $this->unbreak( $rv );
440
	}
441
442
	/**
443
	 * Creates the query form in order to quickly switch to a specific article.
444
	 *
445
	 * @return A string containing the HTML for the form
446
	 */
447 2
	private function queryForm() {
448
449 2
		if ( $this->getRequest()->getVal( 'printable' ) === 'yes' ) {
450
			return '';
451
		}
452
453 2
		SMWOutputs::requireResource( 'ext.smw.browse' );
454 2
		$title = SpecialPage::getTitleFor( 'Browse' );
455 2
		return '  <form name="smwbrowse" action="' . htmlspecialchars( $title->getLocalURL() ) . '" method="get">' . "\n" .
456 2
			'    <input type="hidden" name="title" value="' . $title->getPrefixedText() . '"/>' .
457 2
			wfMessage( 'smw_browse_article' )->text() . "<br />\n" .
458 2
		    ' <div class="browse-input-resp"> <div class="input-field"><input type="text" name="article" size="40" id="page_input_box" class="input mw-ui-input" value="' . htmlspecialchars( $this->articletext ) . '" /></div>' .
459 2
		    ' <div class="button-field"><input type="submit" class="input-button mw-ui-button" value="' . wfMessage( 'smw_browse_go' )->text() . "\"/></div></div>\n" .
460 2
		    "  </form>\n";
461
	}
462
463
	/**
464
	 * Replace the last two space characters with unbreakable spaces for beautification.
465
	 *
466
	 * @param[in] $text string  Text to be transformed. Does not need to have spaces
467
	 * @return string  Transformed text
468
	 */
469
	private function unbreak( $text ) {
470
		$nonBreakingSpace = html_entity_decode( '&#160;', ENT_NOQUOTES, 'UTF-8' );
471
		$text = preg_replace( '/[\s]/u', $nonBreakingSpace, $text, - 1, $count );
472
		return $count > 2 ? preg_replace( '/($nonBreakingSpace)/u', ' ', $text, max( 0, $count - 2 ) ):$text;
473
	}
474
475
	/**
476
	 * FIXME MW 1.25
477
	 */
478 2
	private function addExternalHelpLinks() {
479
480 2
		if ( !method_exists( $this, 'addHelpLink' ) || ( $this->getRequest()->getVal( 'printable' ) === 'yes' ) ) {
481
			return null;
482
		}
483
484 2
		if ( $this->subject->isValid() ) {
485
			$link = SpecialPage::getTitleFor( 'ExportRDF', $this->subject->getTitle()->getPrefixedText() )->getLocalUrl( 'syntax=rdf' );
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMWDataValue as the method getTitle() does only exist in the following sub-classes of SMWDataValue: SMWWikiPageValue. 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...
486
487
			$this->getOutput()->setIndicators( array(
488
				Html::rawElement(
489
					'div',
490
					array(
491
						'class' => 'mw-indicator smw-page-indicator-rdflink'
492
					),
493
					Html::rawElement(
494
						'a',
495
						array(
496
							'href' => $link
497
					), 'RDF' )
498
				)
499
			) );
500
		}
501
502 2
		$this->addHelpLink( wfMessage( 'smw-specials-browse-helplink' )->escaped(), true );
503 2
	}
504
505
	protected function getGroupName() {
506
		return 'smw_group';
507
	}
508
}
509