View source
<?php
namespace Drupal\farm_map\Plugin\Field\FieldWidget;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\File\FileSystem;
use Drupal\Core\Form\FormStateInterface;
use Drupal\farm_geo\Traits\WktTrait;
use Drupal\file\FileInterface;
use Drupal\geofield\GeoPHP\GeoPHPInterface;
use Drupal\geofield\Plugin\Field\FieldWidget\GeofieldBaseWidget;
use Drupal\geofield\Plugin\GeofieldBackendManager;
use Drupal\geofield\WktGeneratorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class GeofieldWidget extends GeofieldBaseWidget {
use WktTrait;
protected $fileSystem;
public static $geoPhpTypes = [
'geojson' => 'geojson',
'gpx' => 'gpx',
'kml' => 'kml',
'kmz' => 'kml',
'wkb' => 'wkb',
'wkt' => 'wkt',
];
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, GeoPHPInterface $geophp_wrapper, WktGeneratorInterface $wkt_generator, GeofieldBackendManager $geofield_backend_manager, FileSystem $file_system) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings, $geophp_wrapper, $wkt_generator, $geofield_backend_manager);
$this->fileSystem = $file_system;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['third_party_settings'], $container
->get('geofield.geophp'), $container
->get('geofield.wkt_generator'), $container
->get('plugin.manager.geofield_backend'), $container
->get('file_system'));
}
public static function defaultSettings() {
return [
'display_raw_geometry' => TRUE,
'populate_file_field' => FALSE,
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['display_raw_geometry'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Display raw geometry'),
'#default_value' => $this
->getSetting('display_raw_geometry'),
];
$elements['populate_file_field'] = [
'#type' => 'textfield',
'#title' => $this
->t('File field to populate geometry from.'),
'#default_value' => $this
->getSetting('populate_file_field'),
];
return $elements;
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$field_name = $this->fieldDefinition
->getName();
$field_wrapper_id = Html::getUniqueId($field_name . '_wrapper');
$element['#type'] = 'details';
$element['#title'] = $this
->t('Geometry');
$element['#open'] = TRUE;
$element['#prefix'] = '<div id="' . $field_wrapper_id . '">';
$element['#suffix'] = '</div>';
$form_value = $form_state
->getValue([
$field_name,
$delta,
'value',
]);
$field_value = $items[$delta]->value;
$current_value = $form_value ?? $field_value;
$element['map'] = [
'#type' => 'farm_map',
'#map_type' => 'geofield_widget',
'#map_settings' => [
'wkt' => $current_value,
'behaviors' => [
'wkt' => [
'edit' => TRUE,
'zoom' => TRUE,
],
],
],
];
$display_raw_geometry = $this
->getSetting('display_raw_geometry');
$element['value'] = [
'#type' => $display_raw_geometry ? 'textarea' : 'hidden',
'#title' => $this
->t('Geometry'),
'#default_value' => $current_value,
'#attributes' => [
'data-map-geometry-field' => TRUE,
],
];
$populate_file_field = $this
->getSetting('populate_file_field');
if (!empty($populate_file_field) && !empty($form[$populate_file_field])) {
$element['trigger'] = [
'#type' => 'submit',
'#value' => $this
->t('Import geometry from uploaded files'),
'#submit' => [
[
$this,
'fileParse',
],
],
'#ajax' => [
'wrapper' => $field_wrapper_id,
'callback' => [
$this,
'fileCallback',
],
'message' => $this
->t('Working...'),
],
'#states' => [
'disabled' => [
':input[name="' . $populate_file_field . '[0][fids]"]' => [
'empty' => TRUE,
],
],
],
];
}
return $element;
}
public function fileParse(array &$form, FormStateInterface $form_state) {
$populate_file_field = $this
->getSetting('populate_file_field');
if (empty($populate_file_field)) {
return;
}
$triggering_element = $form_state
->getTriggeringElement();
$element = NestedArray::getValue($form, array_slice($triggering_element['#array_parents'], 0, -1));
$uploaded_files = $form_state
->getValue($populate_file_field);
if (!empty($uploaded_files)) {
$file_ids = array_reduce($uploaded_files, function ($carry, $file) {
return array_merge($carry, array_values($file['fids']));
}, []);
$files = \Drupal::entityTypeManager()
->getStorage('file')
->loadMultiple($file_ids);
$wkt_strings = [];
if (!empty($files)) {
foreach ($files as $file) {
$geophp_type = $this
->getGeoPhpType($file);
if ($geophp_type === FALSE) {
$this
->messenger()
->addWarning($this
->t('%filename is not a supported geometry file format. Supported formats: %formats', [
'%filename' => $file
->getFilename(),
'%formats' => implode(', ', array_keys(static::$geoPhpTypes)),
]));
return;
}
$path = $file
->getFileUri();
if ($geophp_type == 'kml' && $file
->getMimeType() === 'application/vnd.google-earth.kmz' && extension_loaded('zip')) {
$path = 'zip://' . $this->fileSystem
->realpath($path) . '#doc.kml';
}
$data = file_get_contents($path);
if ($geom = $this->geoPhpWrapper
->load($data, $geophp_type)) {
$wkt_strings[] = $geom
->out('wkt');
}
}
}
$wkt = '';
if (!empty($wkt_strings)) {
if (count($wkt_strings) > 1) {
$wkt = $this
->combineWkt($wkt_strings);
}
else {
$wkt = reset($wkt_strings);
}
}
if (empty($wkt)) {
$this
->messenger()
->addWarning($this
->t('No geometry could be parsed from %filename.', [
'%filename' => $file
->getFilename(),
]));
return;
}
$field_name = $this->fieldDefinition
->getName();
$delta = $element['#delta'];
$user_input = $form_state
->getUserInput();
unset($user_input[$field_name][$delta]['value']);
$form_state
->setUserInput($user_input);
$form_state
->setValue([
$field_name,
$delta,
'value',
], $wkt);
$form_state
->setRebuild(TRUE);
}
}
public function fileCallback(array &$form, FormStateInterface $form_state) {
$triggering_element = $form_state
->getTriggeringElement();
return NestedArray::getValue($form, array_slice($triggering_element['#array_parents'], 0, -1));
}
private function getGeoPhpType(FileInterface $file) {
$matches = [];
if (preg_match('/(?<=\\.)[^.]+$/', $file
->getFilename(), $matches) && isset($matches[0])) {
if (isset(self::$geoPhpTypes[$matches[0]])) {
return self::$geoPhpTypes[$matches[0]];
}
}
return FALSE;
}
}