You are here

public function MongodbSessionHandler::write in MongoDB 8

Overrides SessionHandler::write

File

mongodb_user/src/MongodbSessionHandler.php, line 99
Contains \Drupal\mongodb_user\MongodbSessionHandler.

Class

MongodbSessionHandler

Namespace

Drupal\mongodb_user

Code

public function write($sid, $value) {
  $user = \Drupal::currentUser();

  // The exception handler is not active at this point, so we need to do it
  // manually.
  try {

    // sid will be added from $key below.
    $fields = array(
      'uid' => $user
        ->id(),
      'hostname' => $this->requestStack
        ->getCurrentRequest()
        ->getClientIP(),
      'session' => $value,
      'timestamp' => REQUEST_TIME,
    );
    $key = array(
      'sid' => Crypt::hashBase64($sid),
    );
    $this
      ->mongoCollection()
      ->update($key, $key + $fields, array(
      'upsert' => TRUE,
    ));

    // Remove obsolete sessions.
    $this
      ->cleanupObsoleteSessions();

    // Likewise, do not update access time more than once per 180 seconds.
    if ($user
      ->isAuthenticated() && REQUEST_TIME - $user
      ->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {

      /** @var \Drupal\user\UserStorageInterface $storage */
      $storage = \Drupal::entityManager()
        ->getStorage('user');
      $storage
        ->updateLastAccessTimestamp($user, REQUEST_TIME);
    }
    return TRUE;
  } catch (\Exception $exception) {
    require_once DRUPAL_ROOT . '/core/includes/errors.inc';

    // If we are displaying errors, then do so with no possibility of a
    // further uncaught exception being thrown.
    if (error_displayable()) {
      print '<h1>Uncaught exception thrown in session handler.</h1>';
      print '<p>' . Error::renderExceptionSafe($exception) . '</p><hr />';
    }
    return FALSE;
  }
}