Passed
Push — 4.2.x ( 8ccadb )
by Jeroen De
07:31
created

LatLongFormatter::makeDirectionalIfNeeded()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 3
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace DataValues\Geo\Formatters;
6
7
use DataValues\Geo\Values\LatLongValue;
8
use InvalidArgumentException;
9
use ValueFormatters\FormatterOptions;
10
use ValueFormatters\ValueFormatter;
11
12
/**
13
 * Geographical coordinates formatter.
14
 * Formats LatLongValue objects.
15
 *
16
 * Supports the following notations:
17
 * - Degree minute second
18
 * - Decimal degrees
19
 * - Decimal minutes
20
 * - Float
21
 *
22
 * Some code in this class has been borrowed from the
23
 * MapsCoordinateParser class of the Maps extension for MediaWiki.
24
 *
25
 * @since 0.1, renamed in 2.0
26
 *
27
 * @license GPL-2.0-or-later
28
 * @author Jeroen De Dauw < [email protected] >
29
 * @author Addshore
30
 * @author Thiemo Kreuz
31
 */
32
class LatLongFormatter implements ValueFormatter {
33
34
	/**
35
	 * Output formats for use with the self::OPT_FORMAT option.
36
	 */
37
	public const TYPE_FLOAT = 'float';
38
	public const TYPE_DMS = 'dms';
39
	public const TYPE_DM = 'dm';
40
	public const TYPE_DD = 'dd';
41
42
	/**
43
	 * The symbols representing the different directions for usage in directional notation.
44
	 * @since 0.1
45
	 */
46
	public const OPT_NORTH_SYMBOL = 'north';
47
	public const OPT_EAST_SYMBOL = 'east';
48
	public const OPT_SOUTH_SYMBOL = 'south';
49
	public const OPT_WEST_SYMBOL = 'west';
50
51
	/**
52
	 * The symbols representing degrees, minutes and seconds.
53
	 * @since 0.1
54
	 */
55
	public const OPT_DEGREE_SYMBOL = 'degree';
56
	public const OPT_MINUTE_SYMBOL = 'minute';
57
	public const OPT_SECOND_SYMBOL = 'second';
58
59
	/**
60
	 * Flags for use with the self::OPT_SPACING_LEVEL option.
61
	 */
62
	public const OPT_SPACE_LATLONG = 'latlong';
63
	public const OPT_SPACE_DIRECTION = 'direction';
64
	public const OPT_SPACE_COORDPARTS = 'coordparts';
65
66
	/**
67
	 * Option specifying the output format (also referred to as output type). Must be one of the
68
	 * self::TYPE_… constants.
69
	 */
70
	public const OPT_FORMAT = 'geoformat';
71
72
	/**
73
	 * Boolean option specifying if negative coordinates should have minus signs, e.g. "-1°, -2°"
74
	 * (false) or cardinal directions, e.g. "1° S, 2° W" (true). Default is false.
75
	 */
76
	public const OPT_DIRECTIONAL = 'directional';
77
78
	/**
79
	 * Option for the separator character between latitude and longitude. Defaults to a comma.
80
	 */
81
	public const OPT_SEPARATOR_SYMBOL = 'separator';
82
83
	/**
84
	 * Option specifying the amount and position of space characters in the output. Must be an array
85
	 * containing zero or more of the self::OPT_SPACE_… flags.
86
	 */
87
	public const OPT_SPACING_LEVEL = 'spacing';
88
89
	/**
90
	 * Option specifying the precision in fractional degrees. Must be a number or numeric string.
91
	 */
92
	public const OPT_PRECISION = 'precision';
93
94
	private const DEFAULT_PRECISION = 1 / 3600;
95
96
	private $options;
97
98
	public function __construct( FormatterOptions $options = null ) {
99
		$this->options = $options ?? new FormatterOptions();
100
101
		$this->defaultOption( self::OPT_NORTH_SYMBOL, 'N' );
102
		$this->defaultOption( self::OPT_EAST_SYMBOL, 'E' );
103
		$this->defaultOption( self::OPT_SOUTH_SYMBOL, 'S' );
104
		$this->defaultOption( self::OPT_WEST_SYMBOL, 'W' );
105
106
		$this->defaultOption( self::OPT_DEGREE_SYMBOL, '°' );
107
		$this->defaultOption( self::OPT_MINUTE_SYMBOL, "'" );
108
		$this->defaultOption( self::OPT_SECOND_SYMBOL, '"' );
109
110
		$this->defaultOption( self::OPT_FORMAT, self::TYPE_FLOAT );
111
		$this->defaultOption( self::OPT_DIRECTIONAL, false );
112
113
		$this->defaultOption( self::OPT_SEPARATOR_SYMBOL, ',' );
114
		$this->defaultOption( self::OPT_SPACING_LEVEL, [
115
			self::OPT_SPACE_LATLONG,
116
			self::OPT_SPACE_DIRECTION,
117
			self::OPT_SPACE_COORDPARTS,
118
		] );
119
		$this->defaultOption( self::OPT_PRECISION, 0 );
120
121
		// Not used in this component, only here for downstream compatibility reasons
122
		$this->options->defaultOption( ValueFormatter::OPT_LANG, 'en' );
123
	}
124
125
	/**
126
	 * @see ValueFormatter::format
127
	 *
128
	 * Calls formatLatLongValue() using OPT_PRECISION for the $precision parameter.
129
	 *
130
	 * @param LatLongValue $value
131
	 *
132
	 * @return string Plain text
133
	 * @throws InvalidArgumentException
134
	 */
135
	public function format( $value ): string {
136
		if ( !( $value instanceof LatLongValue ) ) {
137
			throw new InvalidArgumentException( 'Data value type mismatch. Expected a LatLongValue.' );
138
		}
139
140
		return $this->formatLatLongValue( $value, $this->getPrecisionFromOptions() );
141
	}
142
143
	private function getPrecisionFromOptions(): float {
144
		$precision = $this->options->getOption( self::OPT_PRECISION );
145
146
		if ( is_string( $precision ) ) {
147
			return (float)$precision;
148
		}
149
150
		if ( is_float( $precision ) || is_int( $precision ) ) {
151
			return $precision;
152
		}
153
154
		return self::DEFAULT_PRECISION;
155
	}
156
157
	/**
158
	 * Formats a LatLongValue with the desired precision.
159
	 *
160
	 * @since 0.5
161
	 *
162
	 * @param LatLongValue $value
163
	 * @param float|int $precision The desired precision, given as fractional degrees.
164
	 *
165
	 * @return string Plain text
166
	 * @throws InvalidArgumentException
167
	 */
168
	public function formatLatLongValue( LatLongValue $value, ?float $precision ): string {
169
		if ( $precision === null || $precision <= 0 || !is_finite( $precision ) ) {
170
			$precision = self::DEFAULT_PRECISION;
171
		}
172
173
		$formatted = implode(
174
			$this->options->getOption( self::OPT_SEPARATOR_SYMBOL ) . $this->getSpacing( self::OPT_SPACE_LATLONG ),
175
			[
176
				$this->formatLatitude( $value->getLatitude(), $precision ),
177
				$this->formatLongitude( $value->getLongitude(), $precision )
178
			]
179
		);
180
181
		return $formatted;
182
	}
183
184
	/**
185
	 * @param string $spacingLevel One of the self::OPT_SPACE_… constants
186
	 *
187
	 * @return string
188
	 */
189
	private function getSpacing( string $spacingLevel ): string {
190
		if ( in_array( $spacingLevel, $this->options->getOption( self::OPT_SPACING_LEVEL ) ) ) {
191
			return ' ';
192
		}
193
		return '';
194
	}
195
196
	private function formatLatitude( float $latitude, float $precision ): string {
197
		return $this->makeDirectionalIfNeeded(
198
			$this->formatCoordinate( $latitude, $precision ),
199
			$this->options->getOption( self::OPT_NORTH_SYMBOL ),
200
			$this->options->getOption( self::OPT_SOUTH_SYMBOL )
201
		);
202
	}
203
204
	private function formatLongitude( float $longitude, float $precision ): string {
205
		return $this->makeDirectionalIfNeeded(
206
			$this->formatCoordinate( $longitude, $precision ),
207
			$this->options->getOption( self::OPT_EAST_SYMBOL ),
208
			$this->options->getOption( self::OPT_WEST_SYMBOL )
209
		);
210
	}
211
212
	private function makeDirectionalIfNeeded( string $coordinate, string $positiveSymbol,
213
		string $negativeSymbol ): string {
214
215
		if ( $this->options->getOption( self::OPT_DIRECTIONAL ) ) {
216
			return $this->makeDirectional( $coordinate, $positiveSymbol, $negativeSymbol );
217
		}
218
219
		return $coordinate;
220
	}
221
222
	private function makeDirectional( string $coordinate, string $positiveSymbol,
223
		string $negativeSymbol ): string {
224
225
		$isNegative = substr( $coordinate, 0, 1 ) === '-';
226
227
		if ( $isNegative ) {
228
			$coordinate = substr( $coordinate, 1 );
229
		}
230
231
		$symbol = $isNegative ? $negativeSymbol : $positiveSymbol;
232
233
		return $coordinate . $this->getSpacing( self::OPT_SPACE_DIRECTION ) . $symbol;
234
	}
235
236
	private function formatCoordinate( float $degrees, float $precision ): string {
237
		// Remove insignificant detail
238
		$degrees = $this->roundDegrees( $degrees, $precision );
239
		$format = $this->options->getOption( self::OPT_FORMAT );
240
241
		if ( $format === self::TYPE_FLOAT ) {
242
			return $this->getInFloatFormat( $degrees );
243
		}
244
245
		if ( $format !== self::TYPE_DD ) {
246
			$precision = $this->getUpdatedPrecision( $precision );
247
		}
248
249
		if ( $format === self::TYPE_DD || $precision >= 1 ) {
250
			return $this->getInDecimalDegreeFormat( $degrees, $precision );
251
		}
252
		if ( $format === self::TYPE_DM || $precision >= 1 / 60 ) {
253
			return $this->getInDecimalMinuteFormat( $degrees, $precision );
254
		}
255
		if ( $format === self::TYPE_DMS ) {
256
			return $this->getInDegreeMinuteSecondFormat( $degrees, $precision );
257
		}
258
259
		throw new InvalidArgumentException( 'Invalid coordinate format specified in the options' );
260
	}
261
262
	private function getUpdatedPrecision( float $precision ): float {
263
		if ( $precision >= 1 - 1 / 60 && $precision < 1 ) {
264
			return 1;
265
		}
266
267
		if ( $precision >= 1 / 60 - 1 / 3600 && $precision < 1 / 60 ) {
268
			return 1 / 60;
269
		}
270
271
		return $precision;
272
	}
273
274
	private function roundDegrees( float $degrees, float $precision ): float {
275
		$sign = $degrees > 0 ? 1 : -1;
276
		$reduced = round( abs( $degrees ) / $precision );
277
		$expanded = $reduced * $precision;
278
279
		return $sign * $expanded;
280
	}
281
282
	private function getInFloatFormat( float $floatDegrees ): string {
283
		$stringDegrees = (string)$floatDegrees;
284
285
		if ( $stringDegrees === '-0' ) {
286
			return '0';
287
		}
288
289
		return $stringDegrees;
290
	}
291
292
	private function getInDecimalDegreeFormat( float $floatDegrees, float $precision ): string {
293
		$degreeDigits = $this->getSignificantDigits( 1, $precision );
294
		$stringDegrees = $this->formatNumber( $floatDegrees, $degreeDigits );
295
296
		return $stringDegrees . $this->options->getOption( self::OPT_DEGREE_SYMBOL );
297
	}
298
299
	private function getInDegreeMinuteSecondFormat( float $floatDegrees, float $precision ): string {
300
		$isNegative = $floatDegrees < 0;
301
		$secondDigits = $this->getSignificantDigits( 3600, $precision );
302
303
		$seconds = round( abs( $floatDegrees ) * 3600, max( 0, $secondDigits ) );
304
		$minutes = (int)( $seconds / 60 );
305
		$degrees = (int)( $minutes / 60 );
306
307
		$seconds -= $minutes * 60;
308
		$minutes -= $degrees * 60;
309
310
		$space = $this->getSpacing( self::OPT_SPACE_COORDPARTS );
311
		$result = $this->formatNumber( $degrees )
312
			. $this->options->getOption( self::OPT_DEGREE_SYMBOL )
313
			. $space
314
			. $this->formatNumber( $minutes )
315
			. $this->options->getOption( self::OPT_MINUTE_SYMBOL )
316
			. $space
317
			. $this->formatNumber( $seconds, $secondDigits )
318
			. $this->options->getOption( self::OPT_SECOND_SYMBOL );
319
320
		if ( $isNegative && ( $degrees + $minutes + $seconds ) > 0 ) {
321
			$result = '-' . $result;
322
		}
323
324
		return $result;
325
	}
326
327
	private function getInDecimalMinuteFormat( float $floatDegrees, float $precision ): string {
328
		$isNegative = $floatDegrees < 0;
329
		$minuteDigits = $this->getSignificantDigits( 60, $precision );
330
331
		$minutes = round( abs( $floatDegrees ) * 60, max( 0, $minuteDigits ) );
332
		$degrees = (int)( $minutes / 60 );
333
334
		$minutes -= $degrees * 60;
335
336
		$space = $this->getSpacing( self::OPT_SPACE_COORDPARTS );
337
		$result = $this->formatNumber( $degrees )
338
			. $this->options->getOption( self::OPT_DEGREE_SYMBOL )
339
			. $space
340
			. $this->formatNumber( $minutes, $minuteDigits )
341
			. $this->options->getOption( self::OPT_MINUTE_SYMBOL );
342
343
		if ( $isNegative && ( $degrees + $minutes ) > 0 ) {
344
			$result = '-' . $result;
345
		}
346
347
		return $result;
348
	}
349
350
	/**
351
	 * @param float|int $unitsPerDegree The number of target units per degree
352
	 * (60 for minutes, 3600 for seconds)
353
	 * @param float|int $degreePrecision
354
	 *
355
	 * @return int The number of digits to show after the decimal point
356
	 * (resp. before, if the result is negative).
357
	 */
358
	private function getSignificantDigits( float $unitsPerDegree, float $degreePrecision ): int {
359
		return (int)ceil( -log10( $unitsPerDegree * $degreePrecision ) );
360
	}
361
362
	/**
363
	 * @param float $number
364
	 * @param int $digits The number of digits after the decimal point.
365
	 *
366
	 * @return string
367
	 */
368
	private function formatNumber( float $number, int $digits = 0 ): string {
369
		// TODO: use NumberLocalizer
370
		return sprintf( '%.' . ( $digits > 0 ? $digits : 0 ) . 'F', $number );
371
	}
372
373
	/**
374
	 * @param string $option
375
	 * @param mixed $default
376
	 */
377
	private function defaultOption( $option, $default ) {
378
		$this->options->defaultOption( $option, $default );
379
	}
380
381
}
382