Completed
Push — kml ( 3a6c27 )
by Jeroen De
03:09
created

KmlFormatter::locationToKmlPlacemark()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 0
cts 14
cp 0
rs 9.6
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Maps\Presentation;
4
5
use Maps\Elements\Location;
6
7
/**
8
 * @licence GNU GPL v2+
9
 * @author Jeroen De Dauw < [email protected] >
10
 */
11
class KmlFormatter {
12
13
	/**
14
	 * Builds and returns KML representing the set geographical objects.
15
	 */
16
	public function formatLocationsAsKml( Location ...$locations ): string {
17
		$elements = $this->getKmlForLocations( $locations );
18
19
		// http://earth.google.com/kml/2.2
20
		return <<<EOT
21
<?xml version="1.0" encoding="UTF-8"?>
22
<kml xmlns="http://www.opengis.net/kml/2.2">
23
	<Document>
24
		$elements
25
	</Document>
26
</kml>
27
EOT;
28
	}
29
30
	private function getKmlForLocations( array $locations ): string {
31
		return implode(
32
			"\n",
33
			array_map(
34
				function( Location $location ) {
35
					return $this->locationToKmlPlacemark( $location );
36
				},
37
				$locations
38
			)
39
		);
40
	}
41
42
43
	private function locationToKmlPlacemark( Location $location ): string {
44
		// TODO: escaping?
45
		$name = '<name><![CDATA[ ' . $location->getTitle() . ']]></name>';
46
47
		// TODO: escaping?
48
		$description = '<description><![CDATA[ ' . $location->getText() . ']]></description>';
49
50
		$coordinates = '<coordinates>' . htmlspecialchars( $this->getCoordinateString( $location ) ) . '</coordinates>';
51
52
		return <<<EOT
53
		<Placemark>
54
			$name
55
			$description
56
			<Point>
57
				$coordinates
58
			</Point>
59
		</Placemark>
60
		
61
EOT;
62
	}
63
64
	private function getCoordinateString( Location $location ): string {
65
		// lon,lat[,alt]
66
		return $location->getCoordinates()->getLongitude()
67
			. ',' . $location->getCoordinates()->getLatitude()
68
			. ',0';
69
	}
70
71
}
72