-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Geocoders.php
413 lines (360 loc) 路 11.3 KB
/
Geocoders.php
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<?php
namespace Maps;
use DataValues\Geo\Formatters\GeoCoordinateFormatter;
use DataValues\Geo\Parsers\GeoCoordinateParser;
use DataValues\Geo\Values\LatLongValue;
use MapsOldGeocoderAdapter;
use MWException;
use ValueParsers\ParseException;
/**
* Class for geocoder functionality of the Maps extension.
*
* FIXME: this is procedural spaghetti
*
* @since 0.4
*
* @licence GNU GPL v2+
* @author Jeroen De Dauw < jeroendedauw@gmail.com >
*/
final class Geocoders {
/**
* Associative with geoservice identifiers as keys containing instances of
* the geocoder classes.
*
* Note: This list only contains the instances, so is not to be used for
* looping over all available services, as not all of them are guaranteed
* to have an instance already, use $registeredServices for this purpouse.
*
* @since 0.7
*
* @var Geocoder[]
*/
protected static $geocoders = [];
/**
* Associative with geoservice identifiers as keys containing the class
* name of the geocoders. This is used for registration of a geocoder
* without immediately instantiating it.
*
* @since 0.7
*
* @var array of string => string
*/
public static $registeredGeocoders = [];
/**
* The global geocoder cache, holding geocoded data when enabled.
*
* @since 0.7
*
* @var array
*/
private static $globalGeocoderCache = [];
/**
* Can geocoding happen, ie are there any geocoders available.
*
* @since 1.0.3
* @var boolean
*/
protected static $canGeocode = false;
/**
* Returns if this class can do geocoding operations.
* Ie. if there are any geocoders available.
*
* @since 0.7
*
* @return boolean
*/
public static function canGeocode() {
self::init();
return self::$canGeocode;
}
/**
* Gets a list of available geocoders.
*
* @since 1.0.3
*
* @return array
*/
public static function getAvailableGeocoders() {
self::init();
return array_keys( self::$registeredGeocoders );
}
/**
* Initiate the geocoding functionality.
*
* @since 1.0.3
*
* @return boolean Indicates if init happened
*/
public static function init() {
static $initiated = false;
if ( $initiated ) {
return false;
}
$initiated = true;
// Register the geocoders.
\Hooks::run( 'GeocoderFirstCallInit' );
// Determine if there are any geocoders.
self::$canGeocode = count( self::$registeredGeocoders ) > 0;
return true;
}
/**
* This function first determines whether the provided string is a pair or coordinates
* or an address. If it's the later, an attempt to geocode will be made. The function will
* return the coordinates or false, in case a geocoding attempt was made but failed.
*
* @since 0.7
*
* @param string $coordsOrAddress
* @param string $geoservice
* @param string|false $mappingService
* @param boolean $checkForCoords
*
* @return LatLongValue|false
*/
public static function attemptToGeocode( $coordsOrAddress, $geoservice = '', $mappingService = false, $checkForCoords = true ) {
if ( $checkForCoords ) {
$coordinateParser = new GeoCoordinateParser( new \ValueParsers\ParserOptions() );
try {
return $coordinateParser->parse( $coordsOrAddress );
}
catch ( ParseException $parseException ) {
return self::geocode( $coordsOrAddress, $geoservice, $mappingService );
}
} else {
return self::geocode( $coordsOrAddress, $geoservice, $mappingService );
}
}
/**
*
*
* @since 0.7
*
* @param string $coordsOrAddress
* @param string $geoService
* @param string|false $mappingService
*
* @return boolean
*/
public static function isLocation( $coordsOrAddress, $geoService = '', $mappingService = false ) {
return self::attemptToGeocode( $coordsOrAddress, $geoService, $mappingService ) !== false;
}
/**
* Geocodes an address with the provided geocoding service and returns the result
* as a string with the optionally provided format, or false when the geocoding failed.
*
* @since 0.7
*
* @param string $coordsOrAddress
* @param string $service
* @param string $mappingService
* @param boolean $checkForCoords
* @param string $targetFormat The notation to which they should be formatted. Defaults to floats.
* @param boolean $directional Indicates if the target notation should be directional. Defaults to false.
*
* @return string|false
*/
public static function attemptToGeocodeToString( $coordsOrAddress, $service = '', $mappingService = false, $checkForCoords = true, $targetFormat = Maps_COORDS_FLOAT, $directional = false ) {
$geoCoordinate = self::attemptToGeocode( $coordsOrAddress, $service, $mappingService, $checkForCoords );
if ( $geoCoordinate === false ) {
return false;
}
$options = new \ValueFormatters\FormatterOptions( [
GeoCoordinateFormatter::OPT_FORMAT => $targetFormat,
GeoCoordinateFormatter::OPT_DIRECTIONAL => $directional,
GeoCoordinateFormatter::OPT_PRECISION => 1 / 360000
] );
$formatter = new GeoCoordinateFormatter( $options );
return $formatter->format( $geoCoordinate );
}
/**
* Geocodes an address with the provided geocoding service and returns the result
* as an array, or false when the geocoding failed.
*
* FIXME: complexity
*
* @since 0.7
*
* @param string $address
* @param string $geoService
* @param string|false $mappingService
*
* @return LatLongValue|false
* @throws MWException
*/
public static function geocode( $address, $geoService = '', $mappingService = false ) {
if ( !is_string( $address ) ) {
throw new MWException( 'Parameter $address must be a string at ' . __METHOD__ );
}
if ( !self::canGeocode() ) {
return false;
}
$geocoder = self::getValidGeocoderInstance( $geoService );
// This means there was no suitable geocoder found, so return false.
if ( $geocoder === false ) {
return false;
}
if ( $geocoder->hasGlobalCacheSupport() ) {
$cacheResult = self::cacheRead( $address );
// This means the cache returned an already computed set of coordinates.
if ( $cacheResult !== false ) {
assert( $cacheResult instanceof LatLongValue );
return $cacheResult;
}
}
$coordinates = self::getGeocoded( $geocoder, $address );
if ( $coordinates === false ) {
return false;
}
self::cacheWrite( $address, $coordinates );
return $coordinates;
}
private static function getGeocoded( Geocoder $geocoder, $address ) {
$coordinates = self::getGeocodedAsArray( $geocoder, $address );
if ( $coordinates !== false ) {
$coordinates = new LatLongValue(
$coordinates['lat'],
$coordinates['lon']
);
}
return $coordinates;
}
private static function getGeocodedAsArray( Geocoder $geocoder, $address ) {
// Do the actual geocoding via the geocoder.
$coordinates = $geocoder->geocode( $address );
// If there address could not be geocoded, and contains comma's, try again without the comma's.
// This is cause several geocoding services such as geonames do not handle comma's well.
if ( !$coordinates && strpos( $address, ',' ) !== false ) {
$coordinates = $geocoder->geocode( str_replace( ',', '', $address ) );
}
return $coordinates;
}
/**
* Returns already coordinates already known from previous geocoding operations,
* or false if there is no match found in the cache.
*
* @since 0.7
*
* @param string $address
*
* @return LatLongValue|boolean false
*/
protected static function cacheRead( $address ) {
global $egMapsEnableGeoCache;
if ( $egMapsEnableGeoCache && array_key_exists( $address, self::$globalGeocoderCache ) ) {
return self::$globalGeocoderCache[$address];
}
else {
return false;
}
}
/**
* Writes the geocoded result to the cache if the cache is on.
*
* @since 0.7
*
* @param string $address
* @param LatLongValue $coordinates
*/
protected static function cacheWrite( $address, LatLongValue $coordinates ) {
global $egMapsEnableGeoCache;
// Add the obtained coordinates to the cache when there is a result and the cache is enabled.
if ( $egMapsEnableGeoCache && $coordinates ) {
self::$globalGeocoderCache[$address] = $coordinates;
}
}
/**
* Registers a geocoder linked to an identifier.
*
* @since 0.7
*
* @param string $geocoderIdentifier
* @param string|\Maps\Geocoders\Geocoder $geocoder
*/
public static function registerGeocoder( $geocoderIdentifier, $geocoder ) {
self::$registeredGeocoders[$geocoderIdentifier] = $geocoder;
}
/**
* Returns the instance of the geocoder linked to the provided identifier
* or the default one when it's not valid. False is returned when there
* are no geocoders available.
*
* @since 0.7
*
* @param string $geocoderIdentifier
*
* @return Geocoder|bool
*/
protected static function getValidGeocoderInstance( $geocoderIdentifier ) {
return self::getGeocoderInstance( self::getValidGeocoderIdentifier( $geocoderIdentifier ) );
}
/**
* Returns the instance of a geocoder. This function assumes there is a
* geocoder linked to the identifier you provide - if you are not sure
* it does, use getValidGeocoderInstance instead.
*
* @since 0.7
*
* @param string $geocoderIdentifier
*
* @return Geocoder|bool
* @throws MWException
*/
protected static function getGeocoderInstance( $geocoderIdentifier ) {
if ( !array_key_exists( $geocoderIdentifier, self::$geocoders ) ) {
if ( array_key_exists( $geocoderIdentifier, self::$registeredGeocoders ) ) {
if ( is_string( self::$registeredGeocoders[$geocoderIdentifier] ) ) {
$geocoder = new self::$registeredGeocoders[$geocoderIdentifier]( $geocoderIdentifier );
}
elseif ( self::$registeredGeocoders[$geocoderIdentifier] instanceof \Maps\Geocoders\Geocoder ) {
$geocoder = new MapsOldGeocoderAdapter(
self::$registeredGeocoders[$geocoderIdentifier],
$geocoderIdentifier
);
}
else {
throw new MWException( 'Need either class name or Geocoder instance' );
}
self::$geocoders[$geocoderIdentifier] = $geocoder;
}
else {
throw new MWException( 'There is geocoder linked to identifier ' . $geocoderIdentifier . '.' );
}
}
return self::$geocoders[$geocoderIdentifier];
}
/**
* Returns a valid geocoder idenifier. If the given one is a valid main identifier,
* it will simply be returned. If it's an alias, it will be turned into the correponding
* main identifier. If it's not recognized at all (or empty), the default will be used.
* Only call this function when there are geocoders available, else an erro will be thrown.
*
* @since 0.7
*
* @param string $geocoderIdentifier
*
* @return string|bool
* @throws MWException
*/
protected static function getValidGeocoderIdentifier( $geocoderIdentifier ) {
global $egMapsDefaultGeoService;
static $validatedDefault = false;
if ( $geocoderIdentifier === '' || !array_key_exists( $geocoderIdentifier, self::$registeredGeocoders ) ) {
if ( !$validatedDefault ) {
if ( !array_key_exists( $egMapsDefaultGeoService, self::$registeredGeocoders ) ) {
$services = array_keys( self::$registeredGeocoders );
$egMapsDefaultGeoService = array_shift( $services );
if ( is_null( $egMapsDefaultGeoService ) ) {
throw new MWException( 'Tried to geocode while there are no geocoders available at ' . __METHOD__ );
}
}
}
if ( array_key_exists( $egMapsDefaultGeoService, self::$registeredGeocoders ) ) {
$geocoderIdentifier = $egMapsDefaultGeoService;
}
else {
return false;
}
}
return $geocoderIdentifier;
}
}