Geofield.php in Geofield 8
File
src/Feeds/Target/Geofield.php
View source
<?php
namespace Drupal\geofield\Feeds\Target;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\feeds\Exception\EmptyFeedException;
use Drupal\feeds\FieldTargetDefinition;
use Drupal\feeds\Plugin\Type\Target\FieldTargetBase;
class Geofield extends FieldTargetBase implements ContainerFactoryPluginInterface {
protected $settings;
protected $messenger;
public function __construct(array $configuration, $plugin_id, array $plugin_definition, MessengerInterface $messenger) {
$this->targetDefinition = $configuration['target_definition'];
$this->settings = $this->targetDefinition
->getFieldDefinition()
->getSettings();
$this->messenger = $messenger;
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('messenger'));
}
protected static function prepareTarget(FieldDefinitionInterface $field_definition) {
return FieldTargetDefinition::createFromFieldDefinition($field_definition)
->addProperty('lat')
->addProperty('lon')
->addProperty('value');
}
protected function prepareValues(array $values) {
$results = [];
$coordinates = [];
foreach ($values as $delta => $columns) {
try {
$this
->prepareValue($delta, $columns);
foreach ($columns as $column => $value) {
if (in_array($column, [
'lat',
'lon',
])) {
foreach ($value as $item) {
$coordinates[$column][] = $item;
}
}
if ($column == 'value') {
$results[]['value'] = $value;
}
}
} catch (EmptyFeedException $e) {
$this->messenger
->addError($e
->getMessage());
return FALSE;
}
}
if (!empty($coordinates)) {
$count_of_coordinates = count($coordinates['lat']);
for ($i = 0; $i < $count_of_coordinates; $i++) {
$results[]['value'] = "POINT (" . $coordinates['lon'][$i] . " " . $coordinates['lat'][$i] . ")";
}
}
return $results;
}
protected function prepareValue($delta, array &$values) {
foreach ($values as $column => $value) {
if (in_array($column, [
'lat',
'lon',
])) {
$separated_coordinates = explode(" ", $value);
$values[$column] = [];
foreach ($separated_coordinates as $coordinate) {
$values[$column][] = (double) $coordinate;
}
}
}
if (count($values['lat']) != count($values['lon'])) {
throw new EmptyFeedException('Latitude and Longitude should be a pair. Change your file and import again.');
}
}
}