View source
<?php
namespace Drupal\ip_geoloc\Plugin\views\argument;
use Drupal\core\form\FormStateInterface;
use Drupal\ip_geoloc\Services\IpGeoLocAPI;
use Drupal\views\Plugin\views\argument\ArgumentPluginBase;
class IpGeoLocPluginStyleMap extends ArgumentPluginBase implements ContainerFactoryPluginInterface {
public $api;
public function __construct(array $configuration, $plugin_id, $plugin_definition, IpGeoLocAPI $api) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->is_handler = TRUE;
$this->api = $api;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('ip_geoloc.api'));
}
protected function defineOptions() {
$options = parent::defineOptions();
$options = parent::option_definition();
$options['type'] = [
'default' => 'postal',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['type'] = [
'#type' => 'select',
'#title' => t('Location attribute to use'),
'#options' => [
'postal_code' => t('Postal code'),
'city_state' => t('City and State/Province'),
'country' => t('Country'),
'lat_long' => t('Latitude, longitude'),
'formatted_address' => t('Formatted address'),
],
'#default_value' => $this->options['type'],
];
}
public function getDefaultArgument() {
$location = $this->api
->getVisitorLocation();
if (!empty($location)) {
switch ($this->options['type']) {
case 'postal_code':
return $location['postal_code'];
case 'city_state':
return $location['city'] . ', ' . $location['region'];
case 'country':
return $location['country'];
case 'lat_long':
return $location['latitude'] . ',' . $location['longitude'];
case 'formatted_address':
return $location['formatted_address'];
}
}
return NULL;
}
}