1<?php
2
3namespace Drupal\Core\Ajax;
4
5use Drupal\Core\Asset\AttachedAssets;
6
7/**
8 * AJAX command for a JavaScript Drupal.message() call.
9 *
10 * Developers should be extra careful if this command and
11 * \Drupal\Core\Ajax\AnnounceCommand are included in the same response. Unless
12 * the `announce` option is set to an empty string (''), this command will
13 * result in the message being announced to screen readers. When combined with
14 * AnnounceCommand, this may result in unexpected behavior. Manual testing with
15 * a screen reader is strongly recommended.
16 *
17 * Here are examples of how to suppress announcements:
18 * @code
19 *   $command = new MessageCommand("I won't be announced", NULL, [
20 *     'announce' => '',
21 *   ]);
22 * @endcode
23 *
24 * @see \Drupal\Core\Ajax\AnnounceCommand
25 *
26 * @ingroup ajax
27 */
28class MessageCommand implements CommandInterface, CommandWithAttachedAssetsInterface {
29
30  /**
31   * The message text.
32   *
33   * @var string
34   */
35  protected $message;
36
37  /**
38   * Whether to clear previous messages.
39   *
40   * @var bool
41   */
42  protected $clearPrevious;
43
44  /**
45   * The query selector for the element the message will appear in.
46   *
47   * @var string
48   */
49  protected $wrapperQuerySelector;
50
51  /**
52   * The options passed to Drupal.message().add().
53   *
54   * @var array
55   */
56  protected $options;
57
58  /**
59   * Constructs a MessageCommand object.
60   *
61   * @param string $message
62   *   The text of the message.
63   * @param string|null $wrapper_query_selector
64   *   The query selector of the element to display messages in when they
65   *   should be displayed somewhere other than the default.
66   *   @see Drupal.Message.defaultWrapper()
67   * @param array $options
68   *   The options passed to Drupal.message().add().
69   * @param bool $clear_previous
70   *   If TRUE, previous messages will be cleared first.
71   */
72  public function __construct($message, $wrapper_query_selector = NULL, array $options = [], $clear_previous = TRUE) {
73    $this->message = $message;
74    $this->wrapperQuerySelector = $wrapper_query_selector;
75    $this->options = $options;
76    $this->clearPrevious = $clear_previous;
77  }
78
79  /**
80   * {@inheritdoc}
81   */
82  public function render() {
83    return [
84      'command' => 'message',
85      'message' => $this->message,
86      'messageWrapperQuerySelector' => $this->wrapperQuerySelector,
87      'messageOptions' => $this->options,
88      'clearPrevious' => $this->clearPrevious,
89    ];
90  }
91
92  /**
93   * {@inheritdoc}
94   */
95  public function getAttachedAssets() {
96    $assets = new AttachedAssets();
97    $assets->setLibraries(['core/drupal.message']);
98    return $assets;
99  }
100
101}
102