summaryrefslogtreecommitdiffstats
path: root/core/modules/shortcut/src/Form/SwitchShortcutSet.php
blob: 726af172cde2480f448a8b0ee57b46f342c05e87 (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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
<?php

namespace Drupal\shortcut\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\shortcut\Entity\ShortcutSet;
use Drupal\shortcut\ShortcutSetStorageInterface;
use Drupal\user\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Builds the shortcut set switch form.
 *
 * @internal
 */
class SwitchShortcutSet extends FormBase {

  /**
   * The account the shortcut set is for.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $user;

  /**
   * The shortcut set storage.
   *
   * @var \Drupal\shortcut\ShortcutSetStorageInterface
   */
  protected $shortcutSetStorage;

  /**
   * Constructs a SwitchShortcutSet object.
   *
   * @param \Drupal\shortcut\ShortcutSetStorageInterface $shortcut_set_storage
   *   The shortcut set storage.
   */
  public function __construct(ShortcutSetStorageInterface $shortcut_set_storage) {
    $this->shortcutSetStorage = $shortcut_set_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity.manager')->getStorage('shortcut_set')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'shortcut_set_switch';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL) {
    $account = $this->currentUser();

    $this->user = $user;

    // Prepare the list of shortcut sets.
    $options = array_map(function (ShortcutSet $set) {
      return $set->label();
    }, $this->shortcutSetStorage->loadMultiple());

    $current_set = shortcut_current_displayed_set($this->user);

    // Only administrators can add shortcut sets.
    $add_access = $account->hasPermission('administer shortcuts');
    if ($add_access) {
      $options['new'] = $this->t('New set');
    }

    $account_is_user = $this->user->id() == $account->id();
    if (count($options) > 1) {
      $form['set'] = [
        '#type' => 'radios',
        '#title' => $account_is_user ? $this->t('Choose a set of shortcuts to use') : $this->t('Choose a set of shortcuts for this user'),
        '#options' => $options,
        '#default_value' => $current_set->id(),
      ];

      $form['label'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Label'),
        '#description' => $this->t('The new set is created by copying items from your default shortcut set.'),
        '#access' => $add_access,
        '#states' => [
          'visible' => [
            ':input[name="set"]' => ['value' => 'new'],
          ],
          'required' => [
            ':input[name="set"]' => ['value' => 'new'],
          ],
        ],
      ];
      $form['id'] = [
        '#type' => 'machine_name',
        '#machine_name' => [
          'exists' => [$this, 'exists'],
          'replace_pattern' => '[^a-z0-9-]+',
          'replace' => '-',
        ],
        // This ID could be used for menu name.
        '#maxlength' => 23,
        '#states' => [
          'required' => [
            ':input[name="set"]' => ['value' => 'new'],
          ],
        ],
        '#required' => FALSE,
      ];

      if (!$account_is_user) {
        $default_set = $this->shortcutSetStorage->getDefaultSet($this->user);
        $form['new']['#description'] = $this->t('The new set is created by copying items from the %default set.', ['%default' => $default_set->label()]);
      }

      $form['actions'] = ['#type' => 'actions'];
      $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Change set'),
      ];
    }
    else {
      // There is only 1 option, so output a message in the $form array.
      $form['info'] = [
        '#markup' => '<p>' . $this->t('You are currently using the %set-name shortcut set.', ['%set-name' => $current_set->label()]) . '</p>',
      ];
    }

    return $form;
  }

  /**
   * Determines if a shortcut set exists already.
   *
   * @param string $id
   *   The set ID to check.
   *
   * @return bool
   *   TRUE if the shortcut set exists, FALSE otherwise.
   */
  public function exists($id) {
    return (bool) $this->shortcutSetStorage->getQuery()
      ->condition('id', $id)
      ->execute();
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if ($form_state->getValue('set') == 'new') {
      // Check to prevent creating a shortcut set with an empty title.
      if (trim($form_state->getValue('label')) == '') {
        $form_state->setErrorByName('label', $this->t('The new set label is required.'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $account = $this->currentUser();

    $account_is_user = $this->user->id() == $account->id();
    if ($form_state->getValue('set') == 'new') {
      // Save a new shortcut set with links copied from the user's default set.
      /* @var \Drupal\shortcut\Entity\ShortcutSet $set */
      $set = $this->shortcutSetStorage->create([
        'id' => $form_state->getValue('id'),
        'label' => $form_state->getValue('label'),
      ]);
      $set->save();
      $replacements = [
        '%user' => $this->user->label(),
        '%set_name' => $set->label(),
        ':switch-url' => $this->url('<current>'),
      ];
      if ($account_is_user) {
        // Only administrators can create new shortcut sets, so we know they have
        // access to switch back.
        drupal_set_message($this->t('You are now using the new %set_name shortcut set. You can edit it from this page or <a href=":switch-url">switch back to a different one.</a>', $replacements));
      }
      else {
        drupal_set_message($this->t('%user is now using a new shortcut set called %set_name. You can edit it from this page.', $replacements));
      }
      $form_state->setRedirect(
        'entity.shortcut_set.customize_form',
        ['shortcut_set' => $set->id()]
      );
    }
    else {
      // Switch to a different shortcut set.
      /* @var \Drupal\shortcut\Entity\ShortcutSet $set */
      $set = $this->shortcutSetStorage->load($form_state->getValue('set'));
      $replacements = [
        '%user' => $this->user->getDisplayName(),
        '%set_name' => $set->label(),
      ];
      drupal_set_message($account_is_user ? $this->t('You are now using the %set_name shortcut set.', $replacements) : $this->t('%user is now using the %set_name shortcut set.', $replacements));
    }

    // Assign the shortcut set to the provided user account.
    $this->shortcutSetStorage->assignUser($set, $this->user);
  }

  /**
   * Checks access for the shortcut set switch form.
   *
   * @param \Drupal\user\UserInterface $user
   *   (optional) The owner of the shortcut set.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function checkAccess(UserInterface $user = NULL) {
    return shortcut_set_switch_access($user);
  }

}