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

SMWSpecialBrowse::displayValue()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 24
ccs 0
cts 14
cp 0
rs 6.7272
cc 7
eloc 14
nc 4
nop 3
crap 56
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
		$dataValue->setContextPage(
279
			$this->subject->getDataItem()
0 ignored issues
show
Compatibility introduced by
$this->subject->getDataItem() of type object<SMWDataItem> is not a sub-type of object<SMWDIWikiPage>. 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...
280
		);
281
282
		$html = $dataValue->getLongHTMLText( $linker );
283
284
		if ( $dataValue->getTypeID() === '_wpg' || $dataValue->getTypeID() === '__sob' ) {
285
			$html .= "&#160;" . SMWInfolink::newBrowsingLink( '+', $dataValue->getLongWikiText() )->getHTML( $linker );
286
		} elseif ( $incoming && $property->isVisible() ) {
287
			$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...
288
		} elseif ( $dataValue->getProperty() instanceof DIProperty && $dataValue->getProperty()->getKey() !== '_INST' ) {
289
			$html .= $dataValue->getInfolinkText( SMW_OUTPUT_HTML, $linker );
290
		}
291
292
		return $html;
293
	}
294
295
	/**
296
	 * Displays the subject that is currently being browsed to.
297
	 *
298
	 * @return A string containing the HTML with the subject line
299
	 */
300
	private function displayHead() {
301
		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...
302
303
		$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...
304
		$html = "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" .
305
			"<tr class=\"smwb-title\"><td colspan=\"2\">\n" .
306
			$this->subject->getLongHTMLText( smwfGetLinker() ) . "\n" .
307
			"</td></tr>\n</table>\n";
308
309
		return $html;
310
	}
311
312
	/**
313
	 * Creates the HTML for the center bar including the links with further navigation options.
314
	 *
315
	 * @return string  HTMl with the center bar
316
	 */
317
	private function displayCenter() {
318
		return "<a name=\"smw_browse_incoming\"></a>\n" .
319
		       "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" .
320
		       "<tr class=\"smwb-center\"><td colspan=\"2\">\n" .
321
		       ( $this->showincoming ?
322
			     $this->linkHere( wfMessage( 'smw_browse_hide_incoming' )->text(), true, false, 0 ):
323
		         $this->linkHere( wfMessage( 'smw_browse_show_incoming' )->text(), true, true, $this->offset ) ) .
324
		       "&#160;\n" . "</td></tr>\n" . "</table>\n";
325
	}
326
327
	/**
328
	 * Creates the HTML for the bottom bar including the links with further navigation options.
329
	 *
330
	 * @param[in] $more bool  Are there more inproperties to be displayed?
331
	 * @return string  HTMl with the bottom bar
332
	 */
333
	private function displayBottom( $more ) {
334
		$html  = "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" .
335
		         "<tr class=\"smwb-center\"><td colspan=\"2\">\n";
336
		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...
337
		if ( !$smwgBrowseShowAll ) {
338
			if ( ( $this->offset > 0 ) || $more ) {
339
				$offset = max( $this->offset - self::$incomingpropertiescount + 1, 0 );
340
				$html .= ( $this->offset == 0 ) ? wfMessage( 'smw_result_prev' )->text():
341
					     $this->linkHere( wfMessage( 'smw_result_prev' )->text(), $this->showoutgoing, true, $offset );
342
				$offset = $this->offset + self::$incomingpropertiescount - 1;
343
				// @todo FIXME: i18n patchwork.
344
				$html .= " &#160;&#160;&#160;  <strong>" . wfMessage( 'smw_result_results' )->text() . " " . ( $this->offset + 1 ) .
345
						 " – " . ( $offset ) . "</strong>  &#160;&#160;&#160; ";
346
				$html .= $more ? $this->linkHere( wfMessage( 'smw_result_next' )->text(), $this->showoutgoing, true, $offset ):wfMessage( 'smw_result_next' )->text();
347
			}
348
		}
349
		$html .= "&#160;\n" . "</td></tr>\n" . "</table>\n";
350
		return $html;
351
	}
352
353
	/**
354
	 * Creates the HTML for a link to this page, with some parameters set.
355
	 *
356
	 * @param[in] $text string  The anchor text for the link
357
	 * @param[in] $out bool  Should the linked to page include outgoing properties?
358
	 * @param[in] $in bool  Should the linked to page include incoming properties?
359
	 * @param[in] $offset int  What is the offset for the incoming properties?
360
	 *
361
	 * @return string  HTML with the link to this page
362
	 */
363
	private function linkHere( $text, $out, $in, $offset ) {
364
		$frag = ( $text == wfMessage( 'smw_browse_show_incoming' )->text() ) ? '#smw_browse_incoming' : '';
365
366
		return Html::element(
367
			'a',
368
			array(
369
				'href' => SpecialPage::getSafeTitleFor( 'Browse' )->getLocalURL( array(
370
					'offset' => $offset,
371
					'dir' => $out ? ( $in ? 'both' : 'out' ) : 'in',
372
					'article' => $this->subject->getLongWikiText()
373
				) ) . $frag
374
			),
375
			$text
376
		);
377
	}
378
379
	/**
380
	 * Creates a Semantic Data object with the incoming properties instead of the
381
	 * usual outproperties.
382
	 *
383
	 * @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...
384
	 */
385
	private function getInData() {
386
		$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...
387
		$options = new SMWRequestOptions();
388
		$options->sort = true;
389
		$options->limit = self::$incomingpropertiescount;
390
		if ( $this->offset > 0 ) {
391
			$options->offset = $this->offset;
392
		}
393
394
		$store = ApplicationFactory::getInstance()->getStore();
395
		$inproperties = $store->getInProperties( $this->subject->getDataItem(), $options );
396
397
		if ( count( $inproperties ) == self::$incomingpropertiescount ) {
398
			$more = true;
399
			array_pop( $inproperties ); // drop the last one
400
		} else {
401
			$more = false;
402
		}
403
404
		$valoptions = new SMWRequestOptions();
405
		$valoptions->sort = true;
406
		$valoptions->limit = self::$incomingvaluescount;
407
408
		foreach ( $inproperties as $property ) {
409
			$values = $store->getPropertySubjects( $property, $this->subject->getDataItem(), $valoptions );
410
			foreach ( $values as $value ) {
411
				$indata->addPropertyObjectValue( $property, $value );
412
			}
413
		}
414
415
		// Added in 2.3
416
		\Hooks::run( 'SMW::Browse::AfterIncomingPropertiesLookupComplete', array( $store, $indata, $valoptions ) );
417
418
		return array( $indata, $more );
419
	}
420
421
	/**
422
	 * Figures out the label of the property to be used. For outgoing ones it is just
423
	 * the text, for incoming ones we try to figure out the inverse one if needed,
424
	 * either by looking for an explicitly stated one or by creating a default one.
425
	 *
426
	 * @param[in] $property SMWPropertyValue  The property of interest
427
	 * @param[in] $incoming bool  If it is an incoming property
428
	 *
429
	 * @return string  The label of the property
430
	 */
431
	private function getPropertyLabel( SMWPropertyValue $property, $incoming = false ) {
432
		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...
433
434
		if ( $incoming && $smwgBrowseShowInverse ) {
435
			$oppositeprop = SMWPropertyValue::makeUserProperty( wfMessage( 'smw_inverse_label_property' )->text() );
436
			$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...
437
			$rv = ( count( $labelarray ) > 0 ) ? $labelarray[0]->getLongWikiText():
438
				wfMessage( 'smw_inverse_label_default', $property->getWikiValue() )->text();
439
		} else {
440
			$rv = $property->getWikiValue();
441
		}
442
443
		return $this->unbreak( $rv );
444
	}
445
446
	/**
447
	 * Creates the query form in order to quickly switch to a specific article.
448
	 *
449
	 * @return A string containing the HTML for the form
450
	 */
451 2
	private function queryForm() {
452
453 2
		if ( $this->getRequest()->getVal( 'printable' ) === 'yes' ) {
454
			return '';
455
		}
456
457 2
		SMWOutputs::requireResource( 'ext.smw.browse' );
458 2
		$title = SpecialPage::getTitleFor( 'Browse' );
459 2
		return '  <form name="smwbrowse" action="' . htmlspecialchars( $title->getLocalURL() ) . '" method="get">' . "\n" .
460 2
			'    <input type="hidden" name="title" value="' . $title->getPrefixedText() . '"/>' .
461 2
			wfMessage( 'smw_browse_article' )->text() . "<br />\n" .
462 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>' .
463 2
		    ' <div class="button-field"><input type="submit" class="input-button mw-ui-button" value="' . wfMessage( 'smw_browse_go' )->text() . "\"/></div></div>\n" .
464 2
		    "  </form>\n";
465
	}
466
467
	/**
468
	 * Replace the last two space characters with unbreakable spaces for beautification.
469
	 *
470
	 * @param[in] $text string  Text to be transformed. Does not need to have spaces
471
	 * @return string  Transformed text
472
	 */
473
	private function unbreak( $text ) {
474
		$nonBreakingSpace = html_entity_decode( '&#160;', ENT_NOQUOTES, 'UTF-8' );
475
		$text = preg_replace( '/[\s]/u', $nonBreakingSpace, $text, - 1, $count );
476
		return $count > 2 ? preg_replace( '/($nonBreakingSpace)/u', ' ', $text, max( 0, $count - 2 ) ):$text;
477
	}
478
479
	/**
480
	 * FIXME MW 1.25
481
	 */
482 2
	private function addExternalHelpLinks() {
483
484 2
		if ( !method_exists( $this, 'addHelpLink' ) || ( $this->getRequest()->getVal( 'printable' ) === 'yes' ) ) {
485
			return null;
486
		}
487
488 2
		if ( $this->subject->isValid() ) {
489
			$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...
490
491
			$this->getOutput()->setIndicators( array(
492
				Html::rawElement(
493
					'div',
494
					array(
495
						'class' => 'mw-indicator smw-page-indicator-rdflink'
496
					),
497
					Html::rawElement(
498
						'a',
499
						array(
500
							'href' => $link
501
					), 'RDF' )
502
				)
503
			) );
504
		}
505
506 2
		$this->addHelpLink( wfMessage( 'smw-specials-browse-helplink' )->escaped(), true );
507 2
	}
508
509
	protected function getGroupName() {
510
		return 'smw_group';
511
	}
512
}
513