Completed
Push — kml ( 3a6c27...afd8e1 )
by Jeroen De
03:22
created

KmlFormatter::escapeValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 0
cts 3
cp 0
rs 10
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>'
51
			. $this->escapeValue( $this->getCoordinateString( $location ) )
52
			. '</coordinates>';
53
54
		return <<<EOT
55
		<Placemark>
56
			$name
57
			$description
58
			<Point>
59
				$coordinates
60
			</Point>
61
		</Placemark>
62
		
63
EOT;
64
	}
65
66
	private function getCoordinateString( Location $location ): string {
67
		// lon,lat[,alt]
68
		return $location->getCoordinates()->getLongitude()
69
			. ',' . $location->getCoordinates()->getLatitude()
70
			. ',0';
71
	}
72
73
	private function escapeValue( string $value ): string {
74
		return htmlspecialchars( $value, ENT_NOQUOTES );
75
	}
76
77
}
78