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

namespace Drupal\simple_sitemap;

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

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

Pawel G's avatar
Pawel G committed
15 16
  use StringTranslationTrait;

17 18 19 20 21 22 23 24 25 26 27 28 29
  /*
   * 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
   */
Pawel G's avatar
Pawel G committed
30
  protected $logger;
31 32 33 34

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

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

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

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

  /**
   * @param $message
63 64 65 66 67 68 69
   * @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
70
  }
Pawel G's avatar
Pawel G committed
71

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