ImageOverlayParser::parse()   A
last analyzed

Complexity

Conditions 5
Paths 9

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 0
cts 16
cp 0
rs 9.1608
c 0
b 0
f 0
cc 5
nc 9
nop 1
crap 30
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace Maps\WikitextParsers;
6
7
use DataValues\Geo\Values\LatLongValue;
8
use Jeroen\SimpleGeocoder\Geocoder;
9
use Maps\LegacyModel\ImageOverlay;
10
use Maps\MapsFactory;
11
use ValueParsers\ParseException;
12
use ValueParsers\ValueParser;
13
14
/**
15
 * @since 3.1
16
 *
17
 * @licence GNU GPL v2+
18
 * @author Jeroen De Dauw < [email protected] >
19
 */
20
class ImageOverlayParser implements ValueParser {
21
22
	private $geocoder;
23
24
	public function __construct( $geocoder = null ) {
25
		$this->geocoder = $geocoder instanceof Geocoder ? $geocoder : MapsFactory::globalInstance()->getGeocoder();
26
	}
27
28
	/**
29
	 * @since 3.1
30
	 *
31
	 * @param string $value
32
	 *
33
	 * @return ImageOverlay
34
	 * @throws ParseException
35
	 */
36
	public function parse( $value ) {
37
		$metaData = explode( '~', $value );
38
		$imageParameters = explode( ':', array_shift( $metaData ), 3 );
39
40
		if ( count( $imageParameters ) !== 3 ) {
41
			throw new ParseException( 'Need 3 parameters for an image overlay' );
42
		}
43
44
		$boundsNorthEast = $this->stringToLatLongValue( $imageParameters[0] );
45
		$boundsSouthWest = $this->stringToLatLongValue( $imageParameters[1] );
46
		$imageUrl = \Maps\MapsFunctions::getFileUrl( $imageParameters[2] );
0 ignored issues
show
Deprecated Code introduced by
The method Maps\MapsFunctions::getFileUrl() has been deprecated.

This method has been deprecated.

Loading history...
47
48
		$overlay = new ImageOverlay( $boundsNorthEast, $boundsSouthWest, $imageUrl );
49
50
		if ( $metaData !== [] ) {
51
			$overlay->setTitle( array_shift( $metaData ) );
52
		}
53
54
		if ( $metaData !== [] ) {
55
			$overlay->setText( array_shift( $metaData ) );
56
		}
57
58
		if ( $metaData !== [] ) {
59
			$overlay->setLink( $this->getUrlFromLinkString( array_shift( $metaData ) ) );
60
		}
61
62
		return $overlay;
63
	}
64
65
	private function getUrlFromLinkString( string $linkString ): string {
66
		$linkPrefix = 'link:';
67
68
		if ( substr( $linkString, 0, strlen( $linkPrefix ) ) === $linkPrefix ) {
69
			return substr( $linkString, strlen( $linkPrefix ) );
70
		}
71
72
		return $linkString;
73
	}
74
75
	private function stringToLatLongValue( string $location ): LatLongValue {
76
		$latLong = $this->geocoder->geocode( $location );
77
78
		if ( $latLong === null ) {
79
			throw new ParseException( 'Failed to parse or geocode' );
80
		}
81
82
		return $latLong;
83
	}
84
85
}
86