Logger.php 2.18 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\simple_sitemap;

5
use Drupal\Core\Messenger\Messenger;
6
use Drupal\Core\StringTranslation\StringTranslationTrait;
gbyte.co's avatar
gbyte.co committed
7 8
use Drupal\Core\Session\AccountProxyInterface;
use Psr\Log\LoggerInterface;
9 10

/**
gbyte.co's avatar
gbyte.co committed
11
 * Class Logger
12 13 14 15
 * @package Drupal\simple_sitemap
 */
class Logger {

gbyte.co's avatar
gbyte.co committed
16 17
  use StringTranslationTrait;

18 19 20 21 22 23 24 25 26 27 28 29 30
  /*
   * Can be debug/info/notice/warning/error.
   */
  const LOG_SEVERITY_LEVEL_DEFAULT = 'notice';

  /*
   * Can be status/warning/error.
   */
  const DISPLAY_MESSAGE_TYPE_DEFAULT = 'status';

  /**
   * @var \Psr\Log\LoggerInterface
   */
31
  protected $logger;
32

33 34 35 36 37
  /**
   * @var \Drupal\Core\Messenger\Messenger
   */
  protected $messenger;

38 39 40
  /**
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
41 42
  protected $currentUser;

43 44 45 46 47 48 49 50 51 52
  /**
   * @var string
   */
  protected $message = '';

  /**
   * @var array
   */
  protected $substitutions = [];

53 54
  /**
   * Logger constructor.
55 56 57
   * @param \Psr\Log\LoggerInterface $logger
   * @param \Drupal\Core\Messenger\Messenger $messenger
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
58
   */
59 60
  public function __construct(
    LoggerInterface $logger,
61
    Messenger $messenger,
62 63
    AccountProxyInterface $current_user
  ) {
64
    $this->logger = $logger;
65
    $this->messenger = $messenger;
66 67 68 69 70
    $this->currentUser = $current_user;
  }

  /**
   * @param $message
71 72 73 74 75 76 77
   * @param array $substitutions
   * @return $this
   */
  public function m($message, $substitutions = []) {
    $this->message = $message;
    $this->substitutions = $substitutions;
    return $this;
78
  }
gbyte.co's avatar
gbyte.co committed
79

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
  /**
   * @param string $logSeverityLevel
   * @return $this
   */
  public function log($logSeverityLevel = self::LOG_SEVERITY_LEVEL_DEFAULT) {
    $this->logger->$logSeverityLevel(strtr($this->message, $this->substitutions));
    return $this;
  }

  /**
   * @param string $displayMessageType
   * @param string $permission
   * @return $this
   */
  public function display($displayMessageType = self::DISPLAY_MESSAGE_TYPE_DEFAULT, $permission = '') {
    if (empty($permission) || $this->currentUser->hasPermission($permission)) {
96
      $this->messenger->addMessage($this->t($this->message, $this->substitutions), $displayMessageType);
97 98 99
    }
    return $this;
  }
100
}