CoordinateValue::loadDataItem()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 7
cts 8
cp 0.875
rs 9.8333
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.0175
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace Maps\SemanticMW;
6
7
use DataValues\Geo\Parsers\LatLongParser;
8
use DataValues\Geo\Values\LatLongValue;
9
use InvalidArgumentException;
10
use Maps\MapsFactory;
11
use Maps\Presentation\MapsDistanceParser;
12
use SMW\Query\Language\Description;
13
use SMW\Query\Language\ThingDescription;
14
use SMW\Query\QueryComparator;
15
use SMWDataItem;
16
use SMWDataValue;
17
use SMWDIGeoCoord;
18
use SMWOutputs;
19
use ValueParsers\ParseException;
20
21
/**
22
 * @property SMWDIGeoCoord m_dataitem
23
 *
24
 * @licence GNU GPL v2+
25
 * @author Jeroen De Dauw < [email protected] >
26
 * @author Markus Krötzsch
27
 */
28
class CoordinateValue extends SMWDataValue {
29
30
	private $wikiValue;
31
32
	/**
33
	 * Overwrite SMWDataValue::getQueryDescription() to be able to process
34
	 * comparators between all values.
35
	 *
36
	 * @param string $value
37
	 *
38
	 * @return Description
39
	 * @throws InvalidArgumentException
40
	 */
41 6
	public function getQueryDescription( $value ) {
42 6
		if ( !is_string( $value ) ) {
43
			throw new InvalidArgumentException( '$value needs to be a string' );
44
		}
45
46 6
		[ $distance, $comparator ] = $this->parseUserValue( $value );
0 ignored issues
show
Bug introduced by
The variable $distance seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
Bug introduced by
The variable $comparator does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
47 6
		$distance = $this->parserDistance( $distance );
0 ignored issues
show
Bug introduced by
The variable $distance seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
48
49 6
		$this->setUserValue( $value );
50
51
		switch ( true ) {
52 6
			case !$this->isValid():
53
				return new ThingDescription();
54 6
			case $distance !== false:
55 3
				return new AreaDescription(
56 3
					$this->getDataItem(),
57
					$comparator,
58
					$distance
59
				);
60
			default:
61 3
				return new CoordinateDescription(
62 3
					$this->getDataItem(),
63 3
					null,
64
					$comparator
65
				);
66
		}
67
	}
68
69
	/**
70
	 * @see SMWDataValue::parseUserValue
71
	 */
72 9
	protected function parseUserValue( $value ) {
73 9
		if ( !is_string( $value ) ) {
74
			throw new InvalidArgumentException( '$value needs to be a string' );
75
		}
76
77 9
		$this->wikiValue = $value;
78
79 9
		$comparator = SMW_CMP_EQ;
80 9
		$distance = false;
81
82 9
		if ( $value === '' ) {
83
			$this->addError( wfMessage( 'smw_novalues' )->text() );
84
		} else {
85 9
			$comparator = QueryComparator::getInstance()->extractComparatorFromString( $value );
86
87 9
			[ $coordinates, $distance ] = $this->findValueParts( $value );
0 ignored issues
show
Bug introduced by
The variable $coordinates does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
88
89 9
			$this->tryParseAndSetDataItem( $coordinates );
90
		}
91
92 9
		return [ $distance, $comparator ];
93
	}
94
95 9
	private function findValueParts( string $value ): array {
96 9
		$parts = explode( '(', $value );
97
98 9
		$coordinates = trim( array_shift( $parts ) );
99 9
		$distance = count( $parts ) > 0 ? trim( array_shift( $parts ) ) : false;
100
101 9
		return [ $coordinates, $distance ];
102
	}
103
104 9
	private function tryParseAndSetDataItem( string $coordinates ) {
105 9
		$parser = new LatLongParser();
106
107
		try {
108 9
			$value = $parser->parse( $coordinates );
109 9
			$this->m_dataitem = new SMWDIGeoCoord( $value->getLatitude(), $value->getLongitude() );
110
		}
111
		catch ( ParseException $parseException ) {
112
			$this->addError( wfMessage( 'maps_unrecognized_coords', $coordinates, 1 )->text() );
113
114
			// Make sure this is always set
115
			// TODO: Why is this needed?!
116
			$this->m_dataitem = new SMWDIGeoCoord( [ 'lat' => 0, 'lon' => 0 ] );
117
		}
118 9
	}
119
120 6
	private function parserDistance( $distance ) {
121 6
		if ( $distance !== false ) {
122 3
			$distance = substr( trim( $distance ), 0, -1 );
123
124 3
			if ( !MapsDistanceParser::isDistance( $distance ) ) {
125
				$this->addError( wfMessage( 'semanticmaps-unrecognizeddistance', $distance )->text() );
126
				$distance = false;
127
			}
128
		}
129
130 6
		return $distance;
131
	}
132
133
	/**
134
	 * @see SMWDataValue::getShortHTMLText
135
	 *
136
	 * @since 0.6
137
	 */
138
	public function getShortHTMLText( $linker = null ) {
139
		return $this->getShortWikiText( $linker );
140
	}
141
142
	/**
143
	 * @see SMWDataValue::getShortWikiText
144
	 */
145 4
	public function getShortWikiText( $linked = null ) {
146 4
		if ( $this->isValid() ) {
147 4
			if ( $this->m_caption === false ) {
148 4
				return $this->getFormattedCoord( $this->m_dataitem );
149
			}
150
151
			return $this->m_caption;
152
		}
153
154
		return $this->getErrorText();
155
	}
156
157
	/**
158
	 * @param SMWDIGeoCoord $dataItem
159
	 * @param string|null $format
160
	 *
161
	 * @return string|null
162
	 */
163 4
	private function getFormattedCoord( SMWDIGeoCoord $dataItem, string $format = null ) {
164 4
		return MapsFactory::globalInstance()->getCoordinateFormatter()->format(
165 4
			new LatLongValue(
166 4
				$dataItem->getLatitude(),
167 4
				$dataItem->getLongitude()
168
			),
169 4
			$format ?? $GLOBALS['smgQPCoodFormat'],
170 4
			$GLOBALS['smgQPCoodDirectional']
171
		);
172
	}
173
174
	/**
175
	 * @see SMWDataValue::getLongHTMLText
176
	 */
177
	public function getLongHTMLText( $linker = null ) {
178
		return $this->getLongWikiText( $linker );
179
	}
180
181
	/**
182
	 * @see SMWDataValue::getLongWikiText
183
	 *
184
	 * @since 0.6
185
	 */
186
	public function getLongWikiText( $linked = null ) {
187
		if ( $this->isValid() ) {
188
			SMWOutputs::requireHeadItem( SMW_HEADER_TOOLTIP );
189
190
			// TODO: fix lang keys so they include the space and coordinates.
191
			$coordinateSet = $this->m_dataitem->getCoordinateSet();
192
193
			$text = $this->getFormattedCoord( $this->m_dataitem );
194
195
			$lines = [
196
				wfMessage( 'semanticmaps-latitude', $coordinateSet['lat'] )->inContentLanguage()->escaped(),
197
				wfMessage( 'semanticmaps-longitude', $coordinateSet['lon'] )->inContentLanguage()->escaped(),
198
			];
199
200
			if ( array_key_exists( 'alt', $coordinateSet ) ) {
201
				$lines[] = wfMessage( 'semanticmaps-altitude', $coordinateSet['alt'] )->inContentLanguage()->escaped();
202
			}
203
204
			return '<span class="smwttinline">' . htmlspecialchars( $text ) . '<span class="smwttcontent">' .
205
				implode( '<br />', $lines ) .
206
				'</span></span>';
207
		} else {
208
			return $this->getErrorText();
209
		}
210
	}
211
212
	/**
213
	 * @see SMWDataValue::getWikiValue
214
	 */
215
	public function getWikiValue() {
216
		return $this->wikiValue;
217
	}
218
219
	/**
220
	 * @see SMWDataValue::setDataItem
221
	 *
222
	 * @param SMWDataItem $dataItem
223
	 *
224
	 * @return boolean
225
	 */
226 4
	protected function loadDataItem( SMWDataItem $dataItem ) {
227 4
		if ( $dataItem instanceof SMWDIGeoCoord ) {
0 ignored issues
show
Bug introduced by
The class SMWDIGeoCoord does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
228 4
			$formattedValue = $this->getFormattedCoord( $dataItem );
229
230 4
			if ( $formattedValue !== null ) {
231 4
				$this->wikiValue = $formattedValue;
232 4
				$this->m_dataitem = $dataItem;
233 4
				return true;
234
			}
235
		}
236
237
		return false;
238
	}
239
240
	/**
241
	 * Create links to mapping services based on a wiki-editable message. The parameters
242
	 * available to the message are:
243
	 *
244
	 * $1: The location in non-directional float notation.
245
	 * $2: The location in directional DMS notation.
246
	 * $3: The latitude in non-directional float notation.
247
	 * $4 The longitude in non-directional float notation.
248
	 *
249
	 * @return array
250
	 */
251
	protected function getServiceLinkParams() {
252
		$coordinateSet = $this->m_dataitem->getCoordinateSet();
253
		return [
254
			$this->getFormattedCoord( $this->m_dataitem, 'float' ), // TODO
255
			$this->getFormattedCoord( $this->m_dataitem, 'dms' ), // TODO
256
			$coordinateSet['lat'],
257
			$coordinateSet['lon']
258
		];
259
	}
260
261
	/**
262
	 * @return SMWDIGeoCoord|\SMWDIError
263
	 */
264 10
	public function getDataItem() {
265 10
		return parent::getDataItem();
266
	}
267
268
}
269