Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
247 changes: 154 additions & 93 deletions src/KmlParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace PlinCode\KmlParser;

use Exception;
use PlinCode\KmlParser\Enums\GeometryType;
use PlinCode\KmlParser\Exceptions\KmlParserException;
use PlinCode\KmlParser\Traits\ParsesCoordinates;
use PlinCode\KmlParser\Validators\KmlValidator;
Expand Down Expand Up @@ -60,7 +61,7 @@ public function loadFromString(string $content): self
$this->xml->registerXPathNamespace('kml', $this->namespace);

return $this;
} catch (\Exception $e) {
} catch (Exception $e) {
libxml_clear_errors();
throw KmlParserException::failedToParse($e->getMessage());
}
Expand Down Expand Up @@ -99,26 +100,16 @@ public function getPlacemarks(): array
'description' => (string) $placemarkXml->description,
];

if ($placemarkXml->Point) {
$coords = (string) $placemarkXml->Point->coordinates;
$coordsArray = explode(',', trim($coords));
$placemark['type'] = 'Point';
$placemark['coordinates'] = [
'longitude' => (float) $coordsArray[0],
'latitude' => (float) $coordsArray[1],
'altitude' => isset($coordsArray[2]) ? (float) $coordsArray[2] : 0,
];
}
foreach (GeometryType::cases() as $type) {
if ($placemarkXml->{$type->value}) {
$geometry = $this->parseGeometry($type, $placemarkXml->{$type->value});

if ($placemarkXml->LineString) {
$coords = (string) $placemarkXml->LineString->coordinates;
$placemark['type'] = 'LineString';
$placemark['coordinates'] = $this->parseLineStringCoordinates($coords);
}
if ($geometry !== null) {
$placemark = array_merge($placemark, $geometry);
}

if ($placemarkXml->Polygon) {
$placemark['type'] = 'Polygon';
$placemark['coordinates'] = $this->parsePolygonCoordinates($placemarkXml->Polygon);
break;
}
}

if ($placemarkXml->styleUrl) {
Expand All @@ -141,6 +132,60 @@ public function getPlacemarks(): array
return $placemarks;
}

/**
* Turn one KML geometry element into its array representation.
*
* @return array<string, mixed>|null
*/
protected function parseGeometry(GeometryType $type, SimpleXMLElement $geometry): ?array
{
return match ($type) {
GeometryType::POINT => [
'type' => $type->value,
'coordinates' => $this->parsePointCoordinates((string) $geometry->coordinates),
],
GeometryType::LINE_STRING => [
'type' => $type->value,
'coordinates' => $this->parseLineStringCoordinates((string) $geometry->coordinates),
],
GeometryType::POLYGON => [
'type' => $type->value,
'coordinates' => $this->parsePolygonCoordinates($geometry),
],
GeometryType::MULTI_GEOMETRY => [
'type' => $type->value,
'geometries' => $this->parseMultiGeometry($geometry),
],
};
}

/**
* A MultiGeometry holds nested geometries instead of coordinates, and KML
* allows those to be MultiGeometry elements in turn.
*
* @return array<int, array<string, mixed>>
*/
protected function parseMultiGeometry(SimpleXMLElement $multiGeometry): array
{
$geometries = [];

foreach ($multiGeometry->children() as $name => $child) {
$type = GeometryType::tryFrom((string) $name);

if ($type === null) {
continue;
}

$geometry = $this->parseGeometry($type, $child);

if ($geometry !== null) {
$geometries[] = $geometry;
}
}

return $geometries;
}

/**
* Get Style Node from the KML
*
Expand Down Expand Up @@ -239,86 +284,32 @@ public function getStyleMaps(): array
public function toGeoJson(): array
{
$features = [];
$placemarks = $this->getPlacemarks();

foreach ($placemarks as $placemark) {
if (isset($placemark['coordinates'])) {
$feature = [
'type' => 'Feature',
'properties' => [
'name' => $placemark['name'],
'description' => $placemark['description'],
],
];

// Set geometry based on type
if ($placemark['type'] === 'Point') {
$feature['geometry'] = [
'type' => 'Point',
'coordinates' => [
$placemark['coordinates']['longitude'],
$placemark['coordinates']['latitude'],
$placemark['coordinates']['altitude'],
],
];
} elseif ($placemark['type'] === 'LineString') {
$coordinates = [];
foreach ($placemark['coordinates'] as $coord) {
$coordinates[] = [
$coord['longitude'],
$coord['latitude'],
$coord['altitude'],
];
}

$feature['geometry'] = [
'type' => 'LineString',
'coordinates' => $coordinates,
];
} elseif ($placemark['type'] === 'Polygon') {
$outerCoordinates = [];
foreach ($placemark['coordinates']['outerBoundary'] as $coord) {
$outerCoordinates[] = [
$coord['longitude'],
$coord['latitude'],
$coord['altitude'],
];
}

$innerCoordinates = [];
foreach ($placemark['coordinates']['innerBoundaries'] as $innerBoundary) {
$innerBoundaryCoords = [];
foreach ($innerBoundary as $coord) {
$innerBoundaryCoords[] = [
$coord['longitude'],
$coord['latitude'],
$coord['altitude'],
];
}
$innerCoordinates[] = $innerBoundaryCoords;
}

$allCoordinates = [$outerCoordinates];
if (! empty($innerCoordinates)) {
$allCoordinates = array_merge($allCoordinates, $innerCoordinates);
}
foreach ($this->getPlacemarks() as $placemark) {
$geometry = $this->toGeoJsonGeometry($placemark);

$feature['geometry'] = [
'type' => 'Polygon',
'coordinates' => $allCoordinates,
];
}
if ($geometry === null) {
continue;
}

if (isset($placemark['styleUrl'])) {
$feature['properties']['styleUrl'] = $placemark['styleUrl'];
}
$feature = [
'type' => 'Feature',
'properties' => [
'name' => $placemark['name'],
'description' => $placemark['description'],
],
'geometry' => $geometry,
];

if (isset($placemark['extendedData'])) {
$feature['properties']['extendedData'] = $placemark['extendedData'];
}
if (isset($placemark['styleUrl'])) {
$feature['properties']['styleUrl'] = $placemark['styleUrl'];
}

$features[] = $feature;
if (isset($placemark['extendedData'])) {
$feature['properties']['extendedData'] = $placemark['extendedData'];
}

$features[] = $feature;
}

return [
Expand All @@ -327,6 +318,76 @@ public function toGeoJson(): array
];
}

/**
* A KML MultiGeometry maps onto a GeoJSON GeometryCollection, which nests
* the same way, so this recurses alongside parseMultiGeometry().
*
* @param array<string, mixed> $geometry
* @return array<string, mixed>|null
*/
protected function toGeoJsonGeometry(array $geometry): ?array
{
return match ($geometry['type'] ?? null) {
GeometryType::POINT->value => [
'type' => 'Point',
'coordinates' => $this->toGeoJsonPosition($geometry['coordinates']),
],
GeometryType::LINE_STRING->value => [
'type' => 'LineString',
'coordinates' => array_map(
fn (array $position) => $this->toGeoJsonPosition($position),
$geometry['coordinates'],
),
],
GeometryType::POLYGON->value => [
'type' => 'Polygon',
'coordinates' => $this->toGeoJsonRings($geometry['coordinates']),
],
GeometryType::MULTI_GEOMETRY->value => [
'type' => 'GeometryCollection',
'geometries' => array_values(array_filter(array_map(
fn (array $child) => $this->toGeoJsonGeometry($child),
$geometry['geometries'],
))),
],
default => null,
};
}

/**
* @param array{longitude: float, latitude: float, altitude: float} $position
* @return array<int, float>
*/
protected function toGeoJsonPosition(array $position): array
{
return [$position['longitude'], $position['latitude'], $position['altitude']];
}

/**
* GeoJSON puts the outer ring first and every inner ring after it.
*
* @param array{outerBoundary: array<int, array<string, float>>, innerBoundaries: array<int, array<int, array<string, float>>>} $boundaries
* @return array<int, array<int, array<int, float>>>
*/
protected function toGeoJsonRings(array $boundaries): array
{
$rings = [
array_map(
fn (array $position) => $this->toGeoJsonPosition($position),
$boundaries['outerBoundary'],
),
];

foreach ($boundaries['innerBoundaries'] as $innerBoundary) {
$rings[] = array_map(
fn (array $position) => $this->toGeoJsonPosition($position),
$innerBoundary,
);
}

return $rings;
}

/**
* Get Document Node from the KML
*
Expand Down
14 changes: 14 additions & 0 deletions src/Traits/ParsesCoordinates.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@

trait ParsesCoordinates
{
/**
* @return array{longitude: float, latitude: float, altitude: float}
*/
protected function parsePointCoordinates(string $coordinates): array
{
$parts = explode(',', trim($coordinates));

return [
'longitude' => (float) $parts[0],
'latitude' => (float) ($parts[1] ?? 0),
'altitude' => isset($parts[2]) ? (float) $parts[2] : 0,
];
}

protected function parseLineStringCoordinates(string $coordinates): array
{
$coords = [];
Expand Down
40 changes: 34 additions & 6 deletions src/Validators/KmlValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,45 @@ public function validate(string $content): void

protected function validatePlacemark(SimpleXMLElement $placemark): void
{
$hasGeometry = false;
foreach (GeometryType::cases() as $type) {
if ($placemark->{$type->value}) {
$hasGeometry = true;
$this->validateGeometryCoordinates($placemark->{$type->value}, $type->value);
break;
$this->validateGeometry($placemark->{$type->value}, $type);

return;
}
}

throw new KmlException('Found Placemark without valid geometry');
}

protected function validateGeometry(SimpleXMLElement $geometry, GeometryType $type): void
{
if ($type === GeometryType::MULTI_GEOMETRY) {
$this->validateMultiGeometry($geometry);

return;
}

$this->validateGeometryCoordinates($geometry, $type->value);
}

/**
* A MultiGeometry carries no coordinates of its own, only nested
* geometries, and KML allows those to be MultiGeometry elements in turn.
*/
protected function validateMultiGeometry(SimpleXMLElement $multiGeometry): void
{
$found = false;

foreach (GeometryType::cases() as $type) {
foreach ($multiGeometry->{$type->value} as $child) {
$found = true;
$this->validateGeometry($child, $type);
}
}

if (! $hasGeometry) {
throw new KmlException('Found Placemark without valid geometry');
if (! $found) {
throw new KmlException('Found MultiGeometry without any geometry');
}
}

Expand Down
Loading