summaryrefslogtreecommitdiffstats
path: root/core/lib/Drupal/Core/Messenger/SessionMessenger.php
blob: fc858fda513f250b2d4ba7a7572374642a5315c7 (plain)
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
<?php

namespace Drupal\Core\Messenger;

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

/**
 * Provides a session-based messenger.
 */
class SessionMessenger implements MessengerInterface {

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

  /**
   * Constructs a new instance.
   *
   * @param \Drupal\Core\Session\SessionManagerInterface
   * @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($_SESSION['messages'][$type])) {
      $_SESSION['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
    // \Drupal\Core\Render\Markup objects are detected.
    if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type][] = $message;
      $this->pageCacheKillSwitch->trigger();
    }

    return $this;
  }

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

    return $messages;
  }

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

    return $messages;
  }

  /**
   * {@inheritdoc}
   */
  public function deleteMessages() {
    unset($_SESSION['messages']);

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function deleteMessagesByType($type) {
    unset($_SESSION['messages'][$type]);

    return $this;
  }

}