StaticMessenger.php 2.48 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
<?php

namespace Drupal\Core\Messenger;

use Drupal\Component\Render\MarkupInterface;
use Drupal\Core\PageCache\ResponsePolicy\KillSwitch;
use Drupal\Core\Render\Markup;

/**
 * Provides a messenger that stores messages for this request only.
 */
class StaticMessenger implements MessengerInterface {

  /**
   * The messages that have been set.
   *
   * @var array[]
   *   Keys are either self::TYPE_STATUS, self::TYPE_WARNING, or
   *   self::TYPE_ERROR. Values are arrays of arrays with the following keys:
   *   - message (string): the message.
   *   - safe (bool): whether the message is marked as safe markup.
   */
  protected $messages = [];

  /**
   * The page caching kill switch.
   *
   * @var \Drupal\Core\PageCache\ResponsePolicy\KillSwitch
   */
  protected $pageCacheKillSwitch;

  /**
   * Constructs a new instance.
   *
   * @param \Drupal\Core\PageCache\ResponsePolicy\KillSwitch $page_cache_kill_switch
   *   The page caching kill switch.
   */
  public function __construct(KillSwitch $page_cache_kill_switch) {
    $this->pageCacheKillSwitch = $page_cache_kill_switch;
  }

  /**
   * {@inheritdoc}
   */
  public function addMessage($message, $type = self::TYPE_STATUS, $repeat = FALSE) {
    if (!isset($this->messages[$type])) {
      $this->messages[$type] = [];
    }

    // Convert strings which are safe to the simplest Markup objects.
    if (!($message instanceof Markup) && $message instanceof MarkupInterface) {
      $message = Markup::create((string) $message);
    }

    // Do not use strict type checking so that equivalent string and
    // MarkupInterface objects are detected.
    if ($repeat || !in_array($message, $this->messages[$type])) {
      $this->messages[$type][] = $message;
      $this->pageCacheKillSwitch->trigger();
    }

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getMessages() {
    $messages = isset($this->messages) ? $this->messages : [];
    foreach ($messages as $type => $messages_by_type) {
      $messages[$type] = $messages_by_type;
    }

    return $messages;
  }

  /**
   * {@inheritdoc}
   */
  public function getMessagesByType($type) {
    $messages = isset($this->messages) && isset($this->messages[$type]) ? $this->messages[$type] : [];

    return $messages;
  }

  /**
   * {@inheritdoc}
   */
  public function deleteMessages() {
    unset($this->messages);

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function deleteMessagesByType($type) {
    unset($this->messages[$type]);

    return $this;
  }

}