message_notification-1.0.1-beta1/src/Controller/NotificationCounterController.php
src/Controller/NotificationCounterController.php
<?php
namespace Drupal\message_notification\Controller;
use Drupal\Component\Datetime\Time;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserDataInterface;
use Drupal\views\Views;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Count user notification.
*/
class NotificationCounterController implements ContainerInjectionInterface {
/**
* Constructs a new NotificationCounterController object.
*
* @param \Drupal\user\UserDataInterface $userData
* The user data service.
* @param \Drupal\Core\Session\AccountInterface $currentUser
* The current user.
* @param \Drupal\Component\Datetime\Time $time
* Provides system time.
*/
public function __construct(
protected readonly UserDataInterface $userData,
protected readonly AccountInterface $currentUser,
protected readonly Time $time
) {}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('user.data'),
$container->get('current_user'),
$container->get('datetime.time')
);
}
/**
* Count user notification.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* A JSON response.
*/
public function count(Request $request) {
$view = Views::getView('notifications');
$timestamp = $this->userData
->get('message_notification', $this->currentUser->id(), 'last_notification_view');
if (is_object($view)) {
$view->setDisplay('notification_counter');
$view->setExposedInput([
'created' => $timestamp ?? 0,
]);
$view->preExecute();
$view->execute();
return new JsonResponse([
'count' => $view->total_rows,
]);
}
throw new NotFoundHttpException();
}
/**
* Count user notification.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* A JSON response.
*/
public function countUpdateLastView(Request $request) {
$timestamp = $this->time->getRequestTime();
$this->userData
->set('message_notification', $this->currentUser->id(), 'last_notification_view', $timestamp);
return new JsonResponse([
'success' => TRUE,
]);
}
}
