Completed
Pull Request — master (#14)
by Jeroen De
16:10
created

SubpageParentAnnotator::addAnnotation()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 22
rs 8.9197
cc 4
eloc 11
nc 3
nop 0
1
<?php
2
3
namespace SBL;
4
5
use SMW\DIWikiPage;
6
use SMW\ParserData;
7
use SMW\DIProperty;
8
use Title;
9
10
/**
11
 * @license GNU GPL v2+
12
 * @since 1.3
13
 *
14
 * @author mwjames
15
 */
16
class SubpageParentAnnotator {
17
18
	/**
19
	 * @var ParserData
20
	 */
21
	private $parserData;
22
23
	/**
24
	 * @var boolean
25
	 */
26
	private $subpageParentAnnotationState = true;
27
28
	/**
29
	 * @since 1.3
30
	 *
31
	 * @param ParserData $parserData
32
	 */
33
	public function __construct( ParserData $parserData ) {
34
		$this->parserData = $parserData;
35
	}
36
37
	/**
38
	 * @since 1.3
39
	 *
40
	 * @param boolean $subpageParentAnnotationState
41
	 */
42
	public function setSubpageParentAnnotationState( $subpageParentAnnotationState ) {
43
		$this->subpageParentAnnotationState = (bool)$subpageParentAnnotationState;
44
	}
45
46
	/**
47
	 * @since  1.3
48
	 */
49
	public function addAnnotation() {
50
51
		$title = $this->parserData->getTitle();
52
53
		if ( !$this->subpageParentAnnotationState || strpos( $title->getText(), '/' ) === false ) {
54
			return;
55
		}
56
57
		$property = DIProperty::newFromUserLabel( SBL_PROP_PARENTPAGE );
58
59
		// Don't override any "man"-made annotation
60
		if ( $this->parserData->getSemanticData()->getPropertyValues( $property ) !== array() ) {
61
			return;
62
		}
63
64
		$this->parserData->getSemanticData()->addPropertyObjectValue(
65
			$property,
66
			DIWikiPage::newFromText( $this->getBaseText( $title ), $title->getNamespace() )
67
		);
68
69
		$this->parserData->pushSemanticDataToParserOutput();
70
	}
71
72
	// Don't rely on Title::getBaseText as it depends on the wgNamespacesWithSubpages
73
	// setting and if set false will return the normal text including its subparts
74
	private function getBaseText( $title ) {
75
76
		$parts = explode( '/', $title->getText() );
77
		# Don't discard the real title if there's no subpage involved
78
		if ( count( $parts ) > 1 ) {
79
			unset( $parts[count( $parts ) - 1] );
80
		}
81
82
		return implode( '/', $parts );
83
	}
84
85
}
86