IpGeoLocController.php in IP Geolocation Views & Maps 8        
                          
                  
                        
  
  
  
  
  
File
  src/Controller/IpGeoLocController.php
  
    View source  
  <?php
namespace Drupal\ip_geoloc\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Component\Utility\Html;
use Drupal\ip_geoloc\Services\IpGeoLocSession;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Component\Utility\Unicode;
class IpGeoLocController extends ControllerBase {
  protected $ipGeolocSession;
  
  public function __construct(IpGeoLocSession $ipGeolocSession) {
    $this->ipGeolocSession = $ipGeolocSession;
  }
  
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('ip_geoloc.session'));
  }
  
  public function currentLocation() {
    $request = \Drupal::request();
    if ($request
      ->get('error') !== NULL) {
      
      $error = Html::escape($_POST['error']);
      $this->ipGeolocSession
        ->setSessionValue('error', $error);
      return new JsonResponse([
        'response' => $error,
      ]);
    }
    
    $location = [
      'ip_address' => $request
        ->getClientIp(),
    ];
    $location_data = $request->request
      ->all();
    foreach ($location_data as $key => $value) {
      
      if (Unicode::substr($key, 0, 3) !== 'js_') {
        $location[Html::escape($key)] = Html::escape($value);
      }
    }
    $location['provider'] = empty($location['country']) ? 'device' : 'device+google';
    $since = $this->ipGeolocSession
      ->getSessionValue('position_pending_since');
    
    
    $location['fixed_address'] = 0;
    $location['is_updated'] = TRUE;
    
    $this->ipGeolocSession
      ->setSessionValue('location', NULL);
    $this->ipGeolocSession
      ->setSessionValue('location', $location);
    
    $this->ipGeolocSession
      ->setSessionValue('position_pending_since', NULL);
    
    return new JsonResponse([]);
  }
  
  public function regionAutocomplete(Request $request) {
    $partial_region = $request->query
      ->get('q');
    $matches = [];
    if (strlen($partial_region) >= 2) {
      $geo_vocabulary_id = \Drupal::state()
        ->get('ip_geoloc_geo_vocabulary_id', 0);
      foreach (taxonomy_get_tree($geo_vocabulary_id) as $term) {
        $term_name = SafeMarkup::checkPlain($term->name);
        
        $is_match = stripos($term_name, $partial_region) !== FALSE;
        if ($is_match) {
          $matches[$term_name] = $term_name;
        }
      }
    }
    return new JsonResponse($matches);
  }
}