Logger.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace Drupal\simple_sitemap;
  3. use Drupal\Core\Messenger\Messenger;
  4. use Drupal\Core\StringTranslation\StringTranslationTrait;
  5. use Drupal\Core\Session\AccountProxyInterface;
  6. use Psr\Log\LoggerInterface;
  7. /**
  8. * Class Logger
  9. * @package Drupal\simple_sitemap
  10. */
  11. class Logger {
  12. use StringTranslationTrait;
  13. /*
  14. * Can be debug/info/notice/warning/error.
  15. */
  16. const LOG_SEVERITY_LEVEL_DEFAULT = 'notice';
  17. /*
  18. * Can be status/warning/error.
  19. */
  20. const DISPLAY_MESSAGE_TYPE_DEFAULT = 'status';
  21. /**
  22. * @var \Psr\Log\LoggerInterface
  23. */
  24. protected $logger;
  25. /**
  26. * @var \Drupal\Core\Messenger\Messenger
  27. */
  28. protected $messenger;
  29. /**
  30. * @var \Drupal\Core\Session\AccountProxyInterface
  31. */
  32. protected $currentUser;
  33. /**
  34. * @var string
  35. */
  36. protected $message = '';
  37. /**
  38. * @var array
  39. */
  40. protected $substitutions = [];
  41. /**
  42. * Logger constructor.
  43. * @param \Psr\Log\LoggerInterface $logger
  44. * @param \Drupal\Core\Messenger\Messenger $messenger
  45. * @param \Drupal\Core\Session\AccountProxyInterface $current_user
  46. */
  47. public function __construct(
  48. LoggerInterface $logger,
  49. Messenger $messenger,
  50. AccountProxyInterface $current_user
  51. ) {
  52. $this->logger = $logger;
  53. $this->messenger = $messenger;
  54. $this->currentUser = $current_user;
  55. }
  56. /**
  57. * @param $message
  58. * @param array $substitutions
  59. * @return $this
  60. */
  61. public function m($message, $substitutions = []) {
  62. $this->message = $message;
  63. $this->substitutions = $substitutions;
  64. return $this;
  65. }
  66. /**
  67. * @param string $logSeverityLevel
  68. * @return $this
  69. */
  70. public function log($logSeverityLevel = self::LOG_SEVERITY_LEVEL_DEFAULT) {
  71. $this->logger->$logSeverityLevel(strtr($this->message, $this->substitutions));
  72. return $this;
  73. }
  74. /**
  75. * @param string $displayMessageType
  76. * @param string $permission
  77. * @return $this
  78. */
  79. public function display($displayMessageType = self::DISPLAY_MESSAGE_TYPE_DEFAULT, $permission = '') {
  80. if (empty($permission) || $this->currentUser->hasPermission($permission)) {
  81. $this->messenger->addMessage($this->t($this->message, $this->substitutions), $displayMessageType);
  82. }
  83. return $this;
  84. }
  85. }