You are here

function IpTracker::save in IP address manager 8.2

Save the IpTrack

Return value

type

File

src/IpTracker.php, line 26

Class

IpTracker

Namespace

Drupal\ip

Code

function save() {
  $ip = $this->request
    ->getClientIp();
  $uid = $this->account
    ->id();
  $iplong = ip2long($ip);
  if (!empty($iplong)) {

    // Check to see if a row exists for this uid/ip combination.
    $sql = "SELECT visits FROM {ip_tracker} WHERE uid = :uid AND ip = :ip";
    $args = array(
      ':uid' => $uid,
      ':ip' => $iplong,
    );
    $visits = $this->connection
      ->query($sql, $args)
      ->fetchField();
    if ($visits) {

      // Update.
      return $this->connection
        ->update('ip_tracker')
        ->fields(array(
        'visits' => $visits + 1,
        'last_visit' => REQUEST_TIME,
      ))
        ->condition('uid', $uid)
        ->condition('ip', $iplong)
        ->execute();
    }
    else {

      // Insert.
      return $this->connection
        ->insert('ip_tracker')
        ->fields(array(
        'uid' => $uid,
        'ip' => $iplong,
        'visits' => 1,
        'first_visit' => REQUEST_TIME,
        'last_visit' => REQUEST_TIME,
      ))
        ->execute();
    }
  }
}