summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/DataValues/ValueValidators/PropertySpecificationConstraintValueValidator.php
blob: b58903d95c410c582b38810226e062d017c8381c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php

namespace SMW\DataValues\ValueValidators;

use SMWDataValue as DataValue;

/**
 * @private
 *
 * @license GNU GPL v2+
 * @since 2.5
 *
 * @author mwjames
 */
class PropertySpecificationConstraintValueValidator implements ConstraintValueValidator {

	/**
	 * @var boolean
	 */
	private $hasConstraintViolation = false;

	/**
	 * @var array
	 */
	private static $inMemoryLabelToLanguageTracer = [];

	/**
	 * @since 2.5
	 *
	 * {@inheritDoc}
	 */
	public function hasConstraintViolation() {
		return $this->hasConstraintViolation;
	}

	/**
	 * @since 2.5
	 *
	 * {@inheritDoc}
	 */
	public function validate( $dataValue ) {

		$this->hasConstraintViolation = false;

		if (
			!$dataValue instanceof DataValue ||
			$dataValue->getProperty() === null ||
			$dataValue->getContextPage() === null ||
			$dataValue->getContextPage()->getNamespace() !== SMW_NS_PROPERTY ) {
			return $this->hasConstraintViolation;
		}

		if ( $dataValue->getProperty()->getKey() === '_PPLB' ) {
			return $this->doValidateCodifiedPreferredPropertyLabelConstraints( $dataValue );
		}
	}

	private function doValidateCodifiedPreferredPropertyLabelConstraints( $dataValue ) {

		// Annotated but not enabled
		if ( !$dataValue->isEnabledFeature( SMW_DV_PPLB ) ) {
			return $dataValue->addErrorMsg(
				[
					'smw-datavalue-feature-not-supported',
					'SMW_DV_PPLB'
				]
			);
		}

		$value = $dataValue->toArray();
		$dbKey = $dataValue->getContextPage()->getDBKey();

		// Language has been already assigned!
		if ( ( $isKnownBy = $this->isKnownByLabelAndLanguage( $value, $dbKey ) ) !== false ) {
			$dataValue->addErrorMsg(
				[
					'smw-property-preferred-label-language-combination-exists',
					$value['_TEXT'],
					$value['_LCODE'],
					$isKnownBy
				]
			);
		}
	}

	private function isKnownByLabelAndLanguage( $value, $dbkey ) {

		$lang = isset( $value['_LCODE'] ) ? $value['_LCODE'] : false;

		if ( !isset( self::$inMemoryLabelToLanguageTracer[$dbkey] ) ) {
			self::$inMemoryLabelToLanguageTracer[$dbkey] = [];
		}

		if ( $lang && !isset( self::$inMemoryLabelToLanguageTracer[$dbkey][$lang] ) ) {
			self::$inMemoryLabelToLanguageTracer[$dbkey][$lang] = $value['_TEXT'];
		}

		if ( $lang && self::$inMemoryLabelToLanguageTracer[$dbkey][$lang] !== $value['_TEXT'] ) {
			return self::$inMemoryLabelToLanguageTracer[$dbkey][$lang];
		}

		return false;
	}

}