Logger.php 1.81 KB
Newer Older
Pawel G's avatar
Pawel G committed
1 2 3 4 5 6 7
<?php

namespace Drupal\simple_sitemap;

use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
Pawel G's avatar
Pawel G committed
8 9
 * Class Logger.
 *
Pawel G's avatar
Pawel G committed
10 11 12 13
 * @package Drupal\simple_sitemap
 */
class Logger {

14 15 16 17 18 19 20 21 22 23
  /*
   * Can be debug/info/notice/warning/error.
   */
  const LOG_SEVERITY_LEVEL_DEFAULT = 'notice';

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

Pawel G's avatar
Pawel G committed
24 25
  use StringTranslationTrait;

26 27 28
  /**
   * @var \Psr\Log\LoggerInterface
   */
Pawel G's avatar
Pawel G committed
29
  protected $logger;
30 31 32 33

  /**
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
Pawel G's avatar
Pawel G committed
34 35
  protected $currentUser;

36 37 38 39 40 41 42 43 44 45
  /**
   * @var string
   */
  protected $message = '';

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

Pawel G's avatar
Pawel G committed
46 47
  /**
   * Logger constructor.
Pawel G's avatar
Pawel G committed
48
   *
Pawel G's avatar
Pawel G committed
49
   * @param $logger
50
   * @param $current_user
Pawel G's avatar
Pawel G committed
51
   */
52 53 54 55
  public function __construct(
    LoggerInterface $logger,
    AccountProxyInterface $current_user
  ) {
Pawel G's avatar
Pawel G committed
56 57 58 59 60 61
    $this->logger = $logger;
    $this->currentUser = $current_user;
  }

  /**
   * @param $message
62 63 64 65 66 67 68
   * @param array $substitutions
   * @return $this
   */
  public function m($message, $substitutions = []) {
    $this->message = $message;
    $this->substitutions = $substitutions;
    return $this;
Pawel G's avatar
Pawel G committed
69
  }
Pawel G's avatar
Pawel G committed
70

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  /**
   * @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)) {
      drupal_set_message($this->t($this->message, $this->substitutions), $displayMessageType);
    }
    return $this;
  }
Pawel G's avatar
Pawel G committed
91
}