You are here

public function RecentlyReadService::insertEntity in Recently Read 8

Custom function to insert or update an entry for recently read.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The viewed entity.

\Drupal\Core\Session\AccountInterface|null $user: The user who read the entity. If NULL then the current user will be used.

Overrides RecentlyReadServiceInterface::insertEntity

File

src/RecentlyReadService.php, line 82

Class

RecentlyReadService
Recently read service.

Namespace

Drupal\recently_read

Code

public function insertEntity(EntityInterface $entity, AccountInterface $user = NULL) {

  // Get configuration and check if RR delete options is count based.
  $config = $this->configFactory
    ->getEditable('recently_read.configuration');
  $maxRecords = NULL;
  if ($config
    ->get('delete_config') == "count") {
    $maxRecords = $config
      ->get('count');
  }

  // Assert a user.
  $user = $user ?? $this->currentUser;

  // If anonymous set user_id to 0 and check for any existing entries.
  if ($user
    ->isAnonymous()) {

    // Ensure something is in $_SESSION, otherwise the session ID will
    // not persist.
    // TODO: Replace this with something cleaner once core provides it.
    // See https://www.drupal.org/node/2865991.
    if (!isset($_SESSION['recently_read'])) {
      $_SESSION['recently_read'] = TRUE;
      $this->sessionManager
        ->start();
    }
    $exists = $this->recentlyReadStorage
      ->loadByProperties([
      'session_id' => $this->sessionManager
        ->getId(),
      'type' => $entity
        ->getEntityTypeId(),
      'entity_id' => $entity
        ->id(),
    ]);
  }
  else {
    $exists = $this->recentlyReadStorage
      ->loadByProperties([
      'user_id' => $user
        ->id(),
      'type' => $entity
        ->getEntityTypeId(),
      'entity_id' => $entity
        ->id(),
    ]);
  }

  // If exists then update created else create new.
  if (!empty($exists)) {
    foreach ($exists as $entry) {
      $entry
        ->setCreatedTime(time())
        ->save();
    }
  }
  else {

    // Create new.
    $recentlyRead = $this->recentlyReadStorage
      ->create([
      'type' => $entity
        ->getEntityTypeId(),
      'user_id' => $user
        ->id(),
      'entity_id' => $entity
        ->id(),
      'session_id' => $user
        ->id() ? 0 : $this->sessionManager
        ->getId(),
      'created' => time(),
    ]);
    $recentlyRead
      ->save();
  }

  // Delete records if there is a limit.
  $userRecords = $this
    ->getRecords($user
    ->id());
  if ($maxRecords && count($userRecords) > $maxRecords) {
    $records = array_slice($userRecords, $maxRecords, count($userRecords));
    $this
      ->deleteRecords($records);
  }
}