alert_message-1.0.x-dev/src/StackMiddleware/AlertMessage.php

src/StackMiddleware/AlertMessage.php
<?php

namespace Drupal\alert_message\StackMiddleware;

use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * Provides a HTTP middleware.
 */
class AlertMessage implements HttpKernelInterface {

  /**
   * Constructs a AlertMessage object.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $httpKernel
   *   The decorated kernel.
   * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cacheTagsInvalidator
   *   The cache tags invalidator service.
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
   */
  public function __construct(
    private readonly HttpKernelInterface $httpKernel,
    private readonly CacheTagsInvalidatorInterface $cacheTagsInvalidator,
    private readonly Connection $database,
  ) {}

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = TRUE): Response {
    if ($this->hasActiveAlertMessages()) {
      $this->cacheTagsInvalidator->invalidateTags(['alert_message']);
    }

    return $this->httpKernel->handle($request, $type, $catch);
  }

  /**
   * Checks for the existence of at least one active alert message.
   *
   * @return bool
   *   TRUE if at least one active alert message exists, FALSE otherwise.
   */
  private function hasActiveAlertMessages(): bool {
    $query = $this->database->select('alert_message_field_data', 'am');
    // Do not fetch data, we just want to know if
    // an alert message exists.
    $query->addExpression('1');
    $query->condition('status', 1);
    $query->range(0, 1);

    return (bool) $query->execute()->fetchField();
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc