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

RectangleParser::parse()   B

Complexity

Conditions 8
Paths 128

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
rs 7.8648
c 0
b 0
f 0
cc 8
nc 128
nop 1
1
<?php
2
3
namespace Maps\Presentation\WikitextParsers;
4
5
use DataValues\Geo\Values\LatLongValue;
6
use Jeroen\SimpleGeocoder\Geocoder;
7
use Maps\Elements\Rectangle;
8
use Maps\MapsFactory;
9
use ValueParsers\ParseException;
10
use ValueParsers\StringValueParser;
11
use ValueParsers\ValueParser;
12
13
/**
14
 * @since 3.0
15
 *
16
 * @licence GNU GPL v2+
17
 * @author Kim Eik
18
 * @author Jeroen De Dauw < [email protected] >
19
 */
20
class RectangleParser implements ValueParser {
21
22
	private $metaDataSeparator = '~';
23
24
	private $geocoder;
25
26
	public function __construct( $geocoder = null ) {
27
		$this->geocoder = $geocoder instanceof Geocoder ? $geocoder : MapsFactory::newDefault()->newGeocoder();
28
	}
29
30
	/**
31
	 * @see StringValueParser::stringParse
32
	 *
33
	 * @since 3.0
34
	 *
35
	 * @param string $value
36
	 *
37
	 * @return Rectangle
38
	 */
39
	public function parse( $value ) {
40
		$metaData = explode( $this->metaDataSeparator, $value );
41
		$rectangleData = explode( ':', array_shift( $metaData ) );
42
43
		$rectangle = new Rectangle(
44
			$this->stringToLatLongValue( $rectangleData[0] ),
45
			$this->stringToLatLongValue( $rectangleData[1] )
46
		);
47
48
		if ( $metaData !== [] ) {
49
			$rectangle->setTitle( array_shift( $metaData ) );
50
		}
51
52
		if ( $metaData !== [] ) {
53
			$rectangle->setText( array_shift( $metaData ) );
54
		}
55
56
		if ( $metaData !== [] ) {
57
			$rectangle->setStrokeColor( array_shift( $metaData ) );
58
		}
59
60
		if ( $metaData !== [] ) {
61
			$rectangle->setStrokeOpacity( array_shift( $metaData ) );
62
		}
63
64
		if ( $metaData !== [] ) {
65
			$rectangle->setStrokeWeight( array_shift( $metaData ) );
66
		}
67
68
		if ( $metaData !== [] ) {
69
			$rectangle->setFillColor( array_shift( $metaData ) );
70
		}
71
72
		if ( $metaData !== [] ) {
73
			$rectangle->setFillOpacity( array_shift( $metaData ) );
74
		}
75
76
		return $rectangle;
77
	}
78
79
	private function stringToLatLongValue( string $location ): LatLongValue {
80
		$latLong = $this->geocoder->geocode( $location );
81
82
		if ( $latLong === null ) {
83
			throw new ParseException( 'Failed to parse or geocode' );
84
		}
85
86
		return $latLong;
87
	}
88
89
}
90