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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
|
<?php
namespace SMW\DataValues\ValueParsers;
use SMW\DataValues\AllowsListValue;
use SMW\MediaWiki\MediaWikiNsContentReader;
/**
* @private
*
* @license GNU GPL v2+
* @since 2.5
*
* @author mwjames
*/
class AllowsListValueParser implements ValueParser {
/**
* @var MediaWikiNsContentReader
*/
private $mediaWikiNsContentReader;
/**
* @var array
*/
private $errors = [];
/**
* @var array
*/
private static $contents = [];
/**
* @since 2.5
*
* @param MediaWikiNsContentReader $mediaWikiNsContentReader
*/
public function __construct( MediaWikiNsContentReader $mediaWikiNsContentReader ) {
$this->mediaWikiNsContentReader = $mediaWikiNsContentReader;
}
/**
* @since 2.5
*
* @return array
*/
public function getErrors() {
return $this->errors;
}
/**
* @since 3.0
*/
public function clear() {
self::$contents = [];
$this->errors = [];
}
/**
* @since 2.5
*
* @param string $userValue
*
* @return string|false
*/
public function parse( $userValue ) {
$this->errors = [];
if ( isset( self::$contents[$userValue] ) ) {
return self::$contents[$userValue];
}
self::$contents[$userValue] = $this->parse_contents(
$userValue,
$this->mediaWikiNsContentReader->read( AllowsListValue::LIST_PREFIX . $userValue )
);
return self::$contents[$userValue];
}
private function parse_contents( $userValue, $contents ) {
if ( $contents === '' ) {
return $this->errors[] = [ 'smw-datavalue-allows-value-list-unknown', $userValue ];
}
if ( $contents{0} === '{' && ( $list = json_decode( $contents, true ) ) && is_array( $list ) ) {
return $list;
}
return $this->parse_string( $userValue, $contents );
}
private function parse_string( $userValue, $contents ) {
$parts = array_map( 'trim', preg_split( "([\n][\s]?)", $contents ) );
$list = [];
foreach ( $parts as $part ) {
// Only recognize those with a * Foo
if ( strpos( $part, '*' ) === false ) {
continue;
}
// Remove * from the content, other processes may use the hierarchy
// indicator something else
$part = trim( str_replace( '*', '', $part ) );
// Allow something like * Foo|Bar
if ( strpos( $part, '|' ) !== false ) {
list( $reference, $val ) = explode( '|', $part, 2 );
$list[$reference] = $val;
} else {
$list[$part] = $part;
}
}
if ( $list === [] ) {
$this->errors[] = [ 'smw-datavalue-allows-value-list-missing-marker', $userValue ];
}
return $list;
}
}
|