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

namespace Drupal\simple_sitemap;

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

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

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

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

26 27
  use StringTranslationTrait;

28 29 30
  /**
   * @var \Psr\Log\LoggerInterface
   */
31
  protected $logger;
32 33 34 35

  /**
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
36 37
  protected $currentUser;

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

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

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

  /**
   * @param $message
64 65 66 67 68 69 70
   * @param array $substitutions
   * @return $this
   */
  public function m($message, $substitutions = []) {
    $this->message = $message;
    $this->substitutions = $substitutions;
    return $this;
71
  }
gbyte.co's avatar
gbyte.co committed
72

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
  /**
   * @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;
  }
93
}