Completed
Pull Request — master (#226)
by Stephan
02:29
created

TreeResultPrinter::getHashOfNodes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 0
1
<?php
2
3
namespace SRF\Formats\Tree;
4
5
/**
6
 * File holding the Tree class.
7
 * @author Stephan Gambke
8
 */
9
use Cdb\Exception;
10
use Html;
11
use SMW\DIProperty;
12
use SMW\DIWikiPage;
13
use SMW\ListResultPrinter;
14
use SMWQueryResult;
15
use Title;
16
17
/**
18
 * Result printer that prints query results as a tree (nested html lists).
19
 *
20
 * The available formats are 'tree', 'ultree', 'oltree'. 'tree' is an alias of
21
 * 'ultree'. In an #ask query the parameter 'parent' must be set to contain the
22
 * name of the property, that gives the parent page of the subject page.
23
 *
24
 */
25
class TreeResultPrinter extends ListResultPrinter {
26
27
	private $standardTemplateParameters;
28
29
	/**
30
	 * @var SMWQueryResult | null
31
	 */
32
	private $queryResult = null;
33
34
	/**
35
	 * (non-PHPdoc)
36
	 * @see SMWResultPrinter::getName()
37
	 */
38
	public function getName() {
39
		// Give grep a chance to find the usages:
40
		// srf-printername-tree, srf-printername-ultree, srf-printername-oltree
41
		return \Message::newFromKey( 'srf-printername-' . $this->mFormat )->text();
42
	}
43
44
	/**
45
	 * @return SMWQueryResult
46
	 * @throws Exception
47
	 */
48
	public function getQueryResult() {
49
50
		if ( $this->queryResult === null ) {
51
			throw new Exception( __METHOD__ . ' called outside of ' . __CLASS__ . '::getResultText().');
52
		}
53
54
		return $this->queryResult;
55
	}
56
57
	/**
58
	 * @param SMWQueryResult | null $queryResult
59
	 */
60
	public function setQueryResult( $queryResult ) {
61
		$this->queryResult = $queryResult;
62
	}
63
64
	/**
65
	 * @see ResultPrinter::postProcessParameters()
66
	 */
67
	protected function postProcessParameters() {
68
69
		// FIXME: Missing parent call?
70
71
		// Don't support pagination in trees
72
		$this->mSearchlabel = null;
73
74
		if ( $this->params[ 'template arguments' ] !== 'numbered' ) {
75
76
			if ( filter_var( $this->params[ 'named args' ], FILTER_VALIDATE_BOOLEAN ) === true ) {
77
78
				$this->params[ 'template arguments' ] = 'legacy';
79
80
			} elseif (
81
				$this->params[ 'template arguments' ] !== 'named' &&
82
				$this->params[ 'template arguments' ] !== 'legacy'
83
			) {
84
				// default
85
				$this->params[ 'template arguments' ] = 'numbered';
86
			}
87
88
		}
89
90
		// Allow "_" for encoding spaces, as documented
91
		$this->params[ 'sep' ] = str_replace( '_', ' ', $this->params[ 'sep' ] );
92
93
		$this->hasTemplates =
94
			$this->params[ 'introtemplate' ] !== '' ||
95
			$this->params[ 'outrotemplate' ] !== '' ||
96
			$this->params[ 'template' ] !== '';
97
98
		if ( !ctype_digit( strval( $this->params[ 'start level' ] ) ) || $this->params[ 'start level' ] < 1 ) {
99
			$this->params[ 'start level' ] = 1;
100
		}
101
102
	}
103
104
	/**
105
	 * Return serialised results in specified format.
106
	 * @param SMWQueryResult $queryResult
107
	 * @param $outputmode
108
	 * @return string
109
	 */
110
	protected function getResultText( SMWQueryResult $queryResult, $outputmode ) {
111
112
		$this->setQueryResult( $queryResult );
113
114
		if ( $this->params[ 'parent' ] === '' ) {
115
			$this->addError( 'srf-tree-noparentprop' );
116
			return '';
117
		}
118
119
		$rootHash = $this->getRootHash();
120
121
		if ( $rootHash === false ) {
122
			$this->addError( 'srf-tree-rootinvalid', $this->params[ 'root' ] );
123
			return '';
124
		}
125
126
		if ( $this->hasTemplates ) {
127
			$this->initalizeStandardTemplateParameters();
128
		}
129
130
		$tree = $this->buildTreeFromQueryResult( $rootHash );
131
		$lines = $this->buildLinesFromTree( $tree );
132
133
		// Display default if the result is empty
134
		if ( count( $lines ) === 0 ) {
135
			return $this->params[ 'default' ];
136
		}
137
138
		// FIXME: Linking to further events ($this->linkFurtherResults())
139
		// does not make sense for tree format. But maybe display a warning?
140
141
		$resultText = join( "\n", array_merge(
142
			[ $this->getTemplateCall( $this->params[ 'introtemplate' ] ) ],
143
			$lines,
144
			[ $this->getTemplateCall( $this->params[ 'outrotemplate' ] ) ]
145
		) );
146
147
		$this->setQueryResult( null );
148
149
		return Html::rawElement( 'div', [ 'class' => 'srf-tree' ], $resultText );
150
	}
151
152
	/**
153
	 * @param string $templateName
154
	 * @param string[] $params
155
	 * @return string
156
	 */
157
	public function getTemplateCall( $templateName, $params = [] ) {
158
159
		if ( $templateName === '' ) {
160
			return '';
161
		}
162
163
		return '{{' . $this->mIntroTemplate . join( '|', $params ) . $this->standardTemplateParameters . '}}';
164
	}
165
166
	/**
167
	 * @see SMWResultPrinter::getParamDefinitions
168
	 *
169
	 * @since 1.8
170
	 *
171
	 * @param $definitions array of IParamDefinition
172
	 *
173
	 * @return array of IParamDefinition|array
174
	 */
175
	public function getParamDefinitions( array $definitions ) {
176
		$params = parent::getParamDefinitions( $definitions );
177
178
		$params[ 'parent' ] = [
179
			'default' => '',
180
			'message' => 'srf-paramdesc-tree-parent',
181
		];
182
183
		$params[ 'root' ] = [
184
			'default' => '',
185
			'message' => 'srf-paramdesc-tree-root',
186
		];
187
188
		$params[ 'start level' ] = [
189
			'default' => 1,
190
			'message' => 'srf-paramdesc-tree-startlevel',
191
			'type' => 'integer',
192
		];
193
194
		$params[ 'sep' ] = [
195
			'default' => ', ',
196
			'message' => 'smw-paramdesc-sep',
197
		];
198
199
		return $params;
200
	}
201
202
	/**
203
	 * @param string $rootHash
204
	 * @return TreeNode
205
	 */
206
	protected function buildTreeFromQueryResult( $rootHash ) {
207
208
		$nodes = $this->getHashOfNodes();
209
210
		if ( $rootHash !== '' && !array_key_exists( $rootHash, $nodes ) ) {
211
			return new TreeNode();
212
		}
213
214
		return $this->buildTreeFromNodeList( $rootHash, $nodes );
215
	}
216
217
	/**
218
	 * @return string
219
	 */
220
	protected function getRootHash() {
221
222
		if ( $this->params[ 'root' ] === '' ) {
223
			return '';
224
		}
225
226
		// get the title object of the root page
227
		$rootTitle = Title::newFromText( $this->params[ 'root' ] );
228
229
		if ( $rootTitle !== null ) {
230
			return DIWikiPage::newFromTitle( $rootTitle )->getSerialization();
231
		}
232
233
		return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by SRF\Formats\Tree\TreeResultPrinter::getRootHash of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
234
235
	}
236
237
	/**
238
	 * @return TreeNode[]
239
	 */
240
	protected function getHashOfNodes() {
241
242
		/** @var TreeNode[] $nodes */
243
		$nodes = [];
244
245
		$queryResult = $this->getQueryResult();
246
247
		$row = $queryResult->getNext();
248
		while ( $row !== false ) {
249
			$node = new TreeNode( $row );
250
			$nodes[ $node->getHash() ] = $node;
251
			$row = $queryResult->getNext();
252
		}
253
254
		return $nodes;
255
	}
256
257
	/**
258
	 * Returns a linker object for making hyperlinks
259
	 * @return \Linker
260
	 */
261
	public function getLinker( $firstcol = false ) {
262
		return $this->mLinker;
263
	}
264
265
	/**
266
	 * Depending on current linking settings, returns a linker object
267
	 * for making hyperlinks or NULL if no links should be created.
268
	 *
269
	 * @param int $column Column number
270
	 * @return \Linker|null
271
	 */
272
	public function getLinkerForColumn( $column ) {
273
		return parent::getLinker( $column === 0 );
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getLinker() instead of getLinkerForColumn()). Are you sure this is correct? If so, you might want to change this to $this->getLinker().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
274
	}
275
276
	private function initalizeStandardTemplateParameters() {
277
278
		$query = $this->getQueryResult()->getQuery();
279
280
		$this->standardTemplateParameters =
281
			( $this->params[ 'userparam' ] !== '' ? ( '|userparam' . $this->mUserParam ) : '' ) .
282
			'|smw-resultquerycondition=' . $query->getQueryString() .
283
			'|smw-resultquerylimit=' . $query->getLimit() .
284
			'|smw-resultqueryoffset=' . $query->getOffset();
285
286
	}
287
288
	/**
289
	 * @param string $rootHash
290
	 * @param TreeNode[] $nodes
291
	 * @return TreeNode
292
	 */
293
	protected function buildTreeFromNodeList( $rootHash, $nodes ) {
294
295
		$isRootSpecified = $rootHash !== '';
296
297
		$root = new TreeNode();
298
		if ( $isRootSpecified ) {
299
			$root->addChild( $nodes[ $rootHash ] );
300
		}
301
302
		$store = $this->getQueryResult()->getStore();
303
		$parentPointerProperty = DIProperty::newFromUserLabel( $this->params[ 'parent' ] );
304
305
		foreach ( $nodes as $hash => $node ) {
306
307
			$parents = $store->getPropertyValues(
308
				$node->getResultSubject(), $parentPointerProperty
309
			);
310
311
			if ( empty( $parents ) && !$isRootSpecified ) {
312
313
				$root->addChild( $node );
314
315
			} else {
316
317
				foreach ( $parents as $parent ) {
318
319
					$parentHash = $parent->getSerialization();
320
321
					if ( array_key_exists( $parentHash, $nodes ) ) {
322
						$errorCode = $nodes[ $parentHash ]->addChild( $node );
323
					} elseif ( !$isRootSpecified ) {
324
						$errorCode = $root->addChild( $node );
325
					} else {
326
						// Drop node. It is not part of the tree.
327
						$errorCode = null;
328
					}
329
330
					if ( is_string( $errorCode ) ) {
331
						$this->addError( $errorCode, $node->getResultSubject()->getTitle()->getPrefixedText() );
332
					}
333
				}
334
			}
335
		}
336
		return $root;
337
	}
338
339
	/**
340
	 * @param $tree
341
	 * @return mixed
342
	 */
343
	protected function buildLinesFromTree( $tree ) {
344
		$nodePrinterConfiguration = [
345
			'format' => trim( $this->params[ 'template' ] ),
346
			'template' => trim( $this->params[ 'template' ] ),
347
			'headers' => $this->params[ 'headers' ],
348
			'template arguments' => $this->params[ 'template arguments' ],
349
			'sep' => $this->params[ 'sep' ],
350
		];
351
352
		$visitor = new TreeNodePrinter( $this, $nodePrinterConfiguration );
353
		$lines = $tree->accept( $visitor );
354
		return $lines;
355
	}
356
357
	/**
358
	 * @param string $msgkey
359
	 * @param string | string[] $params
360
	 */
361
	protected function addError( $msgkey, $params = [] ) {
362
363
		parent::addError(
364
			\Message::newFromKey( $msgkey )
365
				->params( $params )
366
				->inContentLanguage()->text()
367
			);
368
	}
369
}
370
371