You are here

IpGeoLocPluginArgDefaultIPGeoLoc.php in IP Geolocation Views & Maps 8

File

src/Plugin/views/argument/IpGeoLocPluginArgDefaultIPGeoLoc.php
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;

/**
 * Default argument plugin to extract a user via menu_get_object.
 *
 * @ingroup views_argument_handlers
 *
 * @ViewsArgument("ip_geoloc_plugin_argument_default_ip_geoloc")
 */
class IpGeoLocPluginStyleMap extends ArgumentPluginBase implements ContainerFactoryPluginInterface {
  public $api;

  /**
   * Constructs a Handler object.
   */
  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;
  }

  /**
   * {@inheritdoc}
   */
  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'));
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options = parent::option_definition();
    $options['type'] = [
      'default' => 'postal',
    ];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  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'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  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;
  }

}

Classes

Namesort descending Description
IpGeoLocPluginStyleMap Default argument plugin to extract a user via menu_get_object.