You are here

IpGeoLocSession.php in IP Geolocation Views & Maps 8

File

src/Services/IpGeoLocSession.php
View source
<?php

namespace Drupal\ip_geoloc\Services;

use Drupal\Core\Extension\ModuleHandler;

/**
 * Class DrupaliseMe.
 */
class IpGeoLocSession {
  protected $moduleHandler;

  /**
   * Constructs a new object. Adds dependency injection.
   */
  public function __construct(ModuleHandler $moduleHandler) {
    $this->moduleHandler = $moduleHandler;
  }

  // @TODO Review session cache api module D8 version

  /**
   * Set a value to the user's SESSION.
   *
   * @param string $name
   *   if FALSE all IPGV&M session variables are deleted;
   *   if NULL the array of all IPGV&M session variables is returned.
   * @param mixed $value
   *   The value to set.
   *
   * @return mixed
   *   The requested or all session variables from ip_geoloc
   */
  public function setSessionValue($name, $value = NULL) {
    if (!$this->moduleHandler
      ->moduleExists('session_cache')) {
      if ($name === FALSE) {
        unset($_SESSION['ip_geoloc']);
      }
      elseif (isset($name)) {
        $_SESSION['ip_geoloc'][$name] = $value;
      }
      return isset($_SESSION) && isset($_SESSION['ip_geoloc']) ? $_SESSION['ip_geoloc'] : NULL;
    }
    if ($name === FALSE) {
      session_cache_set('ip_geoloc', NULL);
      return NULL;
    }

    // Efficiency: for multiple get's during the same request avoid having to go
    // to the storage mechanism each time.
    $variables =& drupal_static(__FUNCTION__, []);
    if (empty($variables)) {
      $variables = session_cache_get('ip_geoloc');
    }
    if (isset($name)) {
      $variables[$name] = $value;
      session_cache_set('ip_geoloc', $variables);
    }
    return $variables;
  }

  /**
   * Get a value from the user's SESSION or all values, if no name is specified.
   *
   * @param string $name
   *   The name of the variable to retrieve.
   *
   * @return mixed
   *   The session value belonging to $name or all session values when name is
   *   omittted.
   */
  public function getSessionValue($name = NULL) {
    $variables = $this
      ->setSessionValue(NULL);
    return empty($name) ? $variables : (isset($variables[$name]) ? $variables[$name] : NULL);
  }

}

Classes

Namesort descending Description
IpGeoLocSession Class DrupaliseMe.