KmlNormalizer.php in farmOS 2.x
File
modules/core/kml/src/Normalizer/KmlNormalizer.php
View source
<?php
namespace Drupal\farm_kml\Normalizer;
use Drupal\farm_geo\GeometryWrapper;
use Drupal\geofield\GeoPHP\GeoPHPInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class KmlNormalizer implements NormalizerInterface, DenormalizerInterface {
const FORMAT = 'geometry_kml';
const TYPE = 'geometry_wrapper';
protected $geoPHP;
public function __construct(GeoPHPInterface $geo_PHP) {
$this->geoPHP = $geo_PHP;
}
public function normalize($object, $format = NULL, array $context = []) {
$kml_string = $object->geometry
->out('kml');
$kml = simplexml_load_string($kml_string);
$kml_name = $kml
->getName();
$kml_value = $kml
->children();
$placemark = [
'#' => [
$kml_name => $kml_value,
],
];
if (isset($object->properties['id'])) {
$placemark['@id'] = $object->properties['id'];
}
$properties = $this
->supportedProperties();
foreach ($properties as $property_name) {
if (isset($object->properties[$property_name])) {
$placemark['#'][$property_name] = $object->properties[$property_name];
}
}
return $placemark;
}
public function supportsNormalization($data, $format = NULL) {
if ($format !== static::FORMAT) {
return FALSE;
}
if (!is_array($data)) {
$data = [
$data,
];
}
$invalid_count = count(array_filter($data, function ($object) {
return !$object instanceof GeometryWrapper;
}));
return $invalid_count === 0;
}
public function denormalize($data, $type, $format = NULL, array $context = []) {
$geometries = [];
foreach ($data as $placemark) {
if (empty($placemark['xml'])) {
continue;
}
$geometry = $this->geoPHP
->load($placemark['xml'], 'kml');
$properties = [];
if (isset($placemark['@attributes']['id'])) {
$properties['id'] = $placemark['@attributes']['id'];
}
$keys = $this
->supportedProperties();
foreach ($keys as $property_name) {
if (isset($placemark[$property_name])) {
$properties[$property_name] = $placemark[$property_name];
}
}
$wrapper = new GeometryWrapper($geometry, $properties);
$geometries[] = $wrapper;
}
return $geometries;
}
public function supportsDenormalization($data, $type, $format = NULL) {
return $type === static::TYPE && $format === static::FORMAT;
}
protected function supportedProperties() {
return [
'name',
'entity_type',
'bundle',
'internal_id',
'description',
];
}
}
Classes
Name |
Description |
KmlNormalizer |
Normalizes GeometryWrapper objects into array for the Kml encoder. |