Completed
Push — move ( b63aae...04f5b5 )
by Jeroen De
16:21 queued 06:23
created

ImageOverlayParser   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 4
dl 0
loc 66
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 2
A parse() 0 28 5
A getUrlFromLinkString() 0 9 2
A stringToLatLongValue() 0 9 2
1
<?php
2
3
namespace Maps\Presentation\WikitextParsers;
4
5
use DataValues\Geo\Values\LatLongValue;
6
use Jeroen\SimpleGeocoder\Geocoder;
7
use Maps\Elements\ImageOverlay;
8
use Maps\MapsFactory;
9
use ValueParsers\ParseException;
10
use ValueParsers\ValueParser;
11
12
/**
13
 * @since 3.1
14
 *
15
 * @licence GNU GPL v2+
16
 * @author Jeroen De Dauw < [email protected] >
17
 */
18
class ImageOverlayParser implements ValueParser {
19
20
	private $geocoder;
21
22
	public function __construct( $geocoder = null ) {
23
		$this->geocoder = $geocoder instanceof Geocoder ? $geocoder : MapsFactory::newDefault()->newGeocoder();
24
	}
25
26
	/**
27
	 * @since 3.1
28
	 *
29
	 * @param string $value
30
	 *
31
	 * @return ImageOverlay
32
	 * @throws ParseException
33
	 */
34
	public function parse( $value ) {
35
		$metaData = explode( '~', $value );
36
		$imageParameters = explode( ':', array_shift( $metaData ), 3 );
37
38
		if ( count( $imageParameters ) !== 3 ) {
39
			throw new ParseException( 'Need 3 parameters for an image overlay' );
40
		}
41
42
		$boundsNorthEast = $this->stringToLatLongValue( $imageParameters[0] );
43
		$boundsSouthWest = $this->stringToLatLongValue( $imageParameters[1] );
44
		$imageUrl = \MapsMapper::getFileUrl( $imageParameters[2] );
0 ignored issues
show
Deprecated Code introduced by
The method MapsMapper::getFileUrl() has been deprecated.

This method has been deprecated.

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