Completed
Push — master ( ad9ce2...b11c6d )
by mw
02:04
created

enableSubpageParentAnnotation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
cc 1
eloc 2
nc 1
nop 1
crap 1
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 $enableSubpageParentAnnotation = true;
27
28
	/**
29
	 * @since 1.3
30
	 *
31
	 * @param ParserData $parserData
32
	 */
33 5
	public function __construct( ParserData $parserData ) {
34 5
		$this->parserData = $parserData;
35 5
	}
36
37
	/**
38
	 * @since 1.3
39
	 *
40
	 * @param boolean $enableSubpageParentAnnotation
41
	 */
42 3
	public function enableSubpageParentAnnotation( $enableSubpageParentAnnotation ) {
43 3
		$this->enableSubpageParentAnnotation = (bool)$enableSubpageParentAnnotation;
44 3
	}
45
46
	/**
47
	 * @since  1.3
48
	 */
49 4
	public function addAnnotation() {
50
51 4
		$title = $this->parserData->getTitle();
52
53 4
		if ( !$this->enableSubpageParentAnnotation || strpos( $title->getText(), '/' ) === false ) {
54 1
			return;
55
		}
56
57 3
		$property = DIProperty::newFromUserLabel( SBL_PROP_PARENTPAGE );
58
59
		// Don't override any "man"-made annotation
60 3
		if ( $this->parserData->getSemanticData()->getPropertyValues( $property ) !== array() ) {
61 1
			return;
62
		}
63
64 2
		$base = $this->getBaseText( $title );
65
66
		// #23
67 2
		if ( substr( $base, -1 ) === ' ' ) {
68 1
			return;
69
		}
70
71 1
		$this->parserData->getSemanticData()->addPropertyObjectValue(
72 1
			$property,
73 1
			DIWikiPage::newFromText( $base, $title->getNamespace() )
74 1
		);
75
76 1
		$this->parserData->pushSemanticDataToParserOutput();
77 1
	}
78
79
	// Don't rely on Title::getBaseText as it depends on the wgNamespacesWithSubpages
80
	// setting and if set false will return the normal text including its subparts
81 2
	private function getBaseText( $title ) {
82
83 2
		$parts = explode( '/', $title->getText() );
84
		# Don't discard the real title if there's no subpage involved
85 2
		if ( count( $parts ) > 1 ) {
86 2
			unset( $parts[count( $parts ) - 1] );
87 2
		}
88
89 2
		return implode( '/', $parts );
90
	}
91
92
}
93