You are here

class RequestController in MongoDB 8.2

The controller for the request events page.

Hierarchy

Expanded class hierarchy of RequestController

File

modules/mongodb_watchdog/src/Controller/RequestController.php, line 22

Namespace

Drupal\mongodb_watchdog\Controller
View source
class RequestController extends ControllerBase {

  /**
   * The core date.formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * A RfcLogLevel instance, to avoid static access.
   *
   * @var \Drupal\Core\Logger\RfcLogLevel
   */
  protected $rfcLogLevel;

  /**
   * The length of the absolute path to the site root, in runes.
   *
   * @var int
   */
  protected $rootLength;

  /**
   * Controller constructor.
   *
   * @param \Psr\Log\LoggerInterface $logger
   *   The logger service, to log intervening events.
   * @param \Drupal\mongodb_watchdog\Logger $watchdog
   *   The MongoDB logger, to load stored events.
   * @param \Drupal\Core\Config\ImmutableConfig $config
   *   The module configuration.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter
   *   The core date.formatter service.
   * @param \Drupal\Core\Pager\PagerManagerInterface $pagerManager
   *   The core pager.manager service.
   * @param \Drupal\Core\Logger\RfcLogLevel $rfcLogLevel
   *   A RfcLogLevel instance, to avoid static access.
   */
  public function __construct(LoggerInterface $logger, Logger $watchdog, ImmutableConfig $config, DateFormatterInterface $dateFormatter, PagerManagerInterface $pagerManager, RfcLogLevel $rfcLogLevel) {
    parent::__construct($logger, $watchdog, $pagerManager, $config);
    $this->dateFormatter = $dateFormatter;
    $this->rfcLogLevel = $rfcLogLevel;

    // Add terminal "/".
    $this->rootLength = mb_strlen(DRUPAL_ROOT) + 1;
  }

  /**
   * Controller.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   * @param string $uniqueId
   *   The unique request id from mod_unique_id. Unsafe.
   *
   * @return array
   *   A render array.
   */
  public function build(Request $request, string $uniqueId) : array {
    if (!preg_match('/^[-\\w@]+$/', $uniqueId)) {
      throw new NotFoundHttpException('Request ID is not well-formed.');
    }
    $events = $this
      ->getRowData($request, $uniqueId);
    if (empty($events)) {
      $top = NULL;
      $main = $this
        ->buildEmpty($this
        ->t('No events found for this request.'));
    }
    else {
      [
        ,
        $first,
      ] = reset($events);
      $top = $this
        ->getTop($uniqueId, $first);
      $main = $this
        ->buildMainTable($events);
    }
    $ret = $this
      ->buildDefaults($main, $top);
    return $ret;
  }

  /**
   * Build the main table.
   *
   * @param array $rows
   *   The event data, as row entries for a "table" element.
   *
   * @return array
   *   A render array for the main table.
   */
  protected function buildMainTable(array $rows) : array {
    $ret = [
      '#header' => $this
        ->buildMainTableHeader(),
      '#rows' => $this
        ->buildMainTableRows($rows),
      '#type' => 'table',
    ];
    return $ret;
  }

  /**
   * Build the main table header.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup[]
   *   A "table" element header array.
   */
  protected function buildMainTableHeader() : array {
    $header = [
      $this
        ->t('Sequence'),
      $this
        ->t('Type'),
      $this
        ->t('Severity'),
      $this
        ->t('Event'),
      $this
        ->t('File'),
      $this
        ->t('Line'),
    ];
    return $header;
  }

  /**
   * Build the main table rows.
   *
   * @param \Drupal\mongodb_watchdog\EventTemplate[]\Drupal\mongodb_watchdog\Event[] $events
   *   A fully loaded array of events and their templates.
   *
   * @return array
   *   A render array for a table.
   */
  protected function buildMainTableRows(array $events) : array {
    $rows = [];
    $levels = $this->rfcLogLevel
      ->getLevels();
    $event = NULL;
    $template = NULL;

    /** @var \Drupal\mongodb_watchdog\EventTemplate $template */

    /** @var \Drupal\mongodb_watchdog\Event $event */
    foreach ($events as [
      $template,
      $event,
    ]) {
      $row = [];
      $row[] = [
        'data' => $event->requestTracking_sequence,
      ];
      $row[] = $template->type;
      $row[] = [
        'data' => $levels[$template->severity],
        'class' => OverviewController::SEVERITY_CLASSES[$template->severity],
      ];
      $row[] = [
        'data' => Link::createFromRoute($template
          ->asString($event->variables), 'mongodb_watchdog.reports.detail', [
          'eventTemplate' => $template->_id,
        ]),
      ];
      $row[] = $this
        ->simplifyPath($event->variables['%file']);
      $row[] = $event->variables['%line'];
      $rows[] = $row;
    }
    return $rows;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) : self {

    /** @var \Psr\Log\LoggerInterface $logger */
    $logger = $container
      ->get('logger.channel.mongodb_watchdog');

    /** @var \Drupal\mongodb_watchdog\Logger $watchdog */
    $watchdog = $container
      ->get(Logger::SERVICE_LOGGER);

    /** @var \Drupal\Core\Config\ImmutableConfig $config */
    $config = $container
      ->get('config.factory')
      ->get('mongodb_watchdog.settings');

    /** @var \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter */
    $dateFormatter = $container
      ->get('date.formatter');

    /** @var \Drupal\Core\Pager\PagerManagerInterface $pagerManager */
    $pagerManager = $container
      ->get('pager.manager');
    $rfcLogLevel = new RfcLogLevel();
    return new static($logger, $watchdog, $config, $dateFormatter, $pagerManager, $rfcLogLevel);
  }

  /**
   * Obtain the data from the logger.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request. Needed for paging.
   * @param string $uniqueId
   *   The request for which to build the detail page.
   *
   * @return \Drupal\mongodb_watchdog\Event[]
   *   The data array.
   */
  protected function getRowData(Request $request, string $uniqueId) : array {
    $count = $this->watchdog
      ->requestEventsCount($uniqueId);
    $page = $this
      ->setupPager($request, $count);
    $skip = $page * $this->itemsPerPage;
    $height = $this->itemsPerPage;
    $events = $this->watchdog
      ->requestEvents($uniqueId, $skip, $height);
    return $events;
  }

  /**
   * Build the heading rows on the per-request event occurrences page.
   *
   * @param string $uniqueId
   *   The unique request id.
   * @param \Drupal\mongodb_watchdog\Event|null $first
   *   A fully loaded array of events and their templates.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup[]
   *   A render array for a table.
   */
  protected function getTop(string $uniqueId = "", ?Event $first = NULL) : array {
    $timestamp = isset($first->timestamp) ? $this->dateFormatter
      ->format($first->timestamp, 'long') : $this
      ->t('No information');
    $rows = [
      [
        $this
          ->t('Request ID'),
        $uniqueId,
      ],
      [
        $this
          ->t('Location'),
        $first
          ->location(),
      ],
      [
        $this
          ->t('Date/time'),
        $timestamp,
      ],
    ];
    foreach ($rows as &$row) {
      $row[0] = [
        'data' => $row[0],
        'header' => TRUE,
      ];
    }
    $ret = [
      '#caption' => $this
        ->t('Request'),
      '#rows' => $rows,
      '#type' => 'table',
    ];
    return $ret;
  }

  /**
   * Convert an absolute path to a relative one if below the site root.
   *
   * @param string $path
   *   An absolute path on the filesystem.
   *
   * @return string
   *   A relative path if possible, otherwise the input path.
   */
  public function simplifyPath(string $path) {
    $ret = mb_strpos($path, DRUPAL_ROOT) === 0 ? mb_strpos($path, $this->rootLength) : $path;
    return $ret;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$itemsPerPage protected property The items_per_page configuration value.
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$pagerManager protected property The pager.manager service.
ControllerBase::$stateService protected property The state service.
ControllerBase::$watchdog protected property The MongoDB logger, to load events.
ControllerBase::buildDefaults protected function The default build() implementation.
ControllerBase::buildEmpty protected function Build markup for a message about the lack of results.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::getPage public static function Return a reliable page number based on available data.
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::setupPager public function Set up the pager.
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
RequestController::$dateFormatter protected property The core date.formatter service.
RequestController::$rfcLogLevel protected property A RfcLogLevel instance, to avoid static access.
RequestController::$rootLength protected property The length of the absolute path to the site root, in runes.
RequestController::build public function Controller.
RequestController::buildMainTable protected function Build the main table.
RequestController::buildMainTableHeader protected function Build the main table header.
RequestController::buildMainTableRows protected function Build the main table rows.
RequestController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
RequestController::getRowData protected function Obtain the data from the logger.
RequestController::getTop protected function Build the heading rows on the per-request event occurrences page. Overrides ControllerBase::getTop
RequestController::simplifyPath public function Convert an absolute path to a relative one if below the site root.
RequestController::__construct public function Controller constructor. Overrides ControllerBase::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.