You are here

public function NotificationsWidgetService::logNotification in Notifications widget 8

Stores the data into notification table.

File

src/Services/NotificationsWidgetService.php, line 104

Class

NotificationsWidgetService
Service handler for Notification Logger.

Namespace

Drupal\notifications_widget\Services

Code

public function logNotification($message, $userAction, $entity) {

  // Get logged user session.
  $currentUser = $this->currentUser;
  if ($entity
    ->bundle() == 'user') {
    $entityUid = $entity
      ->id();
  }
  elseif (method_exists($entity, 'getOwner')) {
    $entityUid = $entity
      ->getOwner()
      ->id();
  }
  else {
    $entityUid = 1;
  }

  // Fetch the excluded entities to notifications.
  $notificationConfig = $this->configFactory
    ->get('notifications_widget.settings');
  $excludeList = $notificationConfig
    ->get('excluded_entities');
  $excludeBundles = explode(',', $excludeList);
  if ($message['content_link'] == '[entity:url]') {
    $entityUrl = $entity
      ->toUrl()
      ->toString();
  }
  else {
    $entityUrl = $message['content_link'];
  }

  // Valildate for bundle exclusion.
  if (!in_array($entity
    ->bundle(), $excludeBundles)) {

    // Prepare notification item link.
    $messageItems = '<a class="noti-store-msg" href="javascript:;" data-link="' . $entityUrl . '">' . $message['content'] . '</a>';
    $messageItems = $this->token
      ->replace($messageItems, [
      'user' => $this->currentUser,
      'node' => $entity,
      'comment' => $entity,
    ]);
    $keys = [
      'id' => NULL,
    ];
    $fields = [
      'entity_id' => $message['id'],
      'entity_uid' => $entityUid,
      'action' => $userAction,
      'bundle' => $message['bundle'],
      'uid' => $currentUser
        ->id(),
      'user_name' => $currentUser
        ->getDisplayName(),
      'message' => $messageItems,
      'status' => 0,
      'created' => $this->time
        ->getRequestTime(),
    ];
    try {
      $this->database
        ->merge('notifications')
        ->key($keys)
        ->fields($fields)
        ->execute();
    } catch (Exception $e) {

      // Exception handling if something else gets thrown.
      $this->loggerFactory
        ->error($e
        ->getMessage());
    }
  }
}