You are here

function filelog_tokens in File Log 8

Same name and namespace in other branches
  1. 2.0.x filelog.tokens.inc \filelog_tokens()

Implements hook_tokens().

1 call to filelog_tokens()
FileLogTokenTest::testTokens in tests/src/Unit/FileLogTokenTest.php
Test the tokens of the log message.

File

./filelog.tokens.inc, line 76
Builds placeholder replacement tokens for log messages.

Code

function filelog_tokens($type, array $tokens, array $data, array $options, BubbleableMetadata $metadata) {
  $token_service = Drupal::token();

  /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_service */
  $date_service = Drupal::service('date.formatter');
  $replacements = [];
  if ($type !== 'log') {
    return [];
  }

  /** @var \Drupal\filelog\LogMessage $message */
  $message = $data['log'];
  foreach ($tokens as $name => $original) {
    switch ($name) {
      case 'type':
        $replacements[$original] = $message
          ->getType();
        break;
      case 'level':
        $replacements[$original] = $message
          ->getLevel();
        break;
      case 'message':
        $replacements[$original] = $message
          ->getText();
        break;
      case 'location':
        $replacements[$original] = $message
          ->getLocation();
        break;
      case 'ip':
        $replacements[$original] = $message
          ->getIp();
        break;

      // Accept both the correct and the RFC spelling here.
      case 'referrer':
      case 'referer':
        $replacements[$original] = $message
          ->getReferrer();
        break;
      case 'created':
        $replacements[$original] = $date_service
          ->format($message
          ->getTimestamp());
        break;
      case 'user':
        $replacements[$original] = $message
          ->getUser()
          ->label();
        break;
    }
  }
  if ($user_tokens = $token_service
    ->findWithPrefix($tokens, 'user')) {
    $replacements += $token_service
      ->generate('user', $user_tokens, [
      'user' => $message
        ->getUser(),
    ], $options, $metadata);
  }
  if ($created_tokens = $token_service
    ->findWithPrefix($tokens, 'created')) {
    $replacements += $token_service
      ->generate('date', $created_tokens, [
      'date' => $message
        ->getTimestamp(),
    ], $options, $metadata);
  }
  if ($variable_tokens = $token_service
    ->findWithPrefix($tokens, 'variable')) {
    foreach ($variable_tokens as $name => $original) {
      $replacements[$original] = $message
        ->getVariable($name);
    }
  }
  if ($variable_tokens = $token_service
    ->findWithPrefix($tokens, 'context')) {
    foreach ($variable_tokens as $name => $original) {
      $replacements[$original] = $message
        ->getContext($name);
    }
  }
  return $replacements;
}