You are here

public function OpignoNotificationController::markReadAll in Opigno notifications 3.x

Same name and namespace in other branches
  1. 8 src/Controller/OpignoNotificationController.php \Drupal\opigno_notification\Controller\OpignoNotificationController::markReadAll()

Ajax callback. Marks all current user notifications as read.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The current request.

Return value

\Drupal\Core\Ajax\AjaxResponse The response object.

1 string reference to 'OpignoNotificationController::markReadAll'
opigno_notification.routing.yml in ./opigno_notification.routing.yml
opigno_notification.routing.yml

File

src/Controller/OpignoNotificationController.php, line 106

Class

OpignoNotificationController
Provides the controller for OpignoNotification entity pages.

Namespace

Drupal\opigno_notification\Controller

Code

public function markReadAll(Request $request) : AjaxResponse {
  $response = new AjaxResponse();
  $notifications = OpignoNotification::getUnreadNotifications();
  foreach ($notifications as $notification) {
    if (!$notification instanceof OpignoNotificationInterface) {
      continue;
    }
    $notification
      ->setHasRead(TRUE);
    try {
      $notification
        ->save();
    } catch (EntityStorageException $e) {
      watchdog_exception('opigno_notification_exception', $e);
    }
  }

  // Reload the page if the user is on Notifications listing page to refresh
  // the view.
  $route = '';
  $url = '';
  if ($request
    ->isXmlHttpRequest()) {
    $url = $request->server
      ->get('HTTP_REFERER');
    $route_info = $this->router
      ->match($url);
    $route = $route_info['_route'] ?? '';
  }
  if ($route === 'view.opigno_notifications.page_all' && $url) {
    $response
      ->addCommand(new RedirectCommand($url));
    return $response;
  }

  // Remove the unread marker in the header and close the dropdown.
  $selector = '.block-notifications__item--notifications .dropdown-menu';
  $response
    ->addCommand(new InvokeCommand($selector, 'addClass', [
    'hidden',
  ]));
  $response
    ->addCommand(new InvokeCommand('.block-notifications__item--notifications .marker', 'addClass', [
    'hidden',
  ]));
  $response
    ->addCommand(new InvokeCommand('.block-notifications__item--notifications .dropdown', 'dropdown', [
    'toggle',
  ]));
  $response
    ->addCommand(new InvokeCommand($selector, 'removeClass', [
    'show',
  ]));
  return $response;
}