foldershare-8.x-1.2/src/Plugin/FolderShareCommand/Rename.php

src/Plugin/FolderShareCommand/Rename.php
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<?php
 
namespace Drupal\foldershare\Plugin\FolderShareCommand;
 
use Drupal\Core\Form\FormStateInterface;
 
use Drupal\foldershare\Settings;
use Drupal\foldershare\Entity\FolderShare;
use Drupal\foldershare\Entity\Exception\RuntimeExceptionWithMarkup;
use Drupal\foldershare\Entity\Exception\ValidationException;
 
/**
 * Defines a command plugin to rename a file or folder.
 *
 * The command sets the name of a single selected entity.
 *
 * Configuration parameters:
 * - 'parentId': the parent folder, if any.
 * - 'selectionIds': selected entity to rename.
 * - 'name': the new name.
 *
 * @ingroup foldershare
 *
 * @FolderShareCommand(
 *  id              = "foldersharecommand_rename",
 *  label           = @Translation("Rename"),
 *  menuNameDefault = @Translation("Rename..."),
 *  menuName        = @Translation("Rename..."),
 *  description     = @Translation("Rename a selected file or folder."),
 *  category        = "edit",
 *  weight          = 20,
 *  parentConstraints = {
 *    "kinds"   = {
 *      "rootlist",
 *      "any",
 *    },
 *    "access"  = "view",
 *  },
 *  selectionConstraints = {
 *    "types"   = {
 *      "parent",
 *      "one",
 *    },
 *    "kinds"   = {
 *      "any",
 *    },
 *    "access"  = "update",
 *  },
 * )
 */
class Rename extends FolderShareCommandBase {
 
  /*--------------------------------------------------------------------
   *
   * Configuration.
   *
   *--------------------------------------------------------------------*/
 
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    // Include room for the new name in the configuration.
    $config = parent::defaultConfiguration();
    $config['name'] = '';
    return $config;
  }
 
  /**
   * {@inheritdoc}
   */
  public function validateParameters() {
    if ($this->parametersValidated === TRUE) {
      return;
    }
 
    // Get the parent folder, if any.
    $parent = $this->getParent();
 
    // Get the selected item. If none, use the parent instead.
    $itemIds = $this->getSelectionIds();
    if (empty($itemIds) === TRUE) {
      $item = $this->getParent();
    }
    else {
      $item = FolderShare::load(reset($itemIds));
    }
 
    // Check if the name is legal. This throws an exception if not valid.
    $newName = $this->configuration['name'];
    $item->checkName($newName);
 
    // Check if the new name is unique within the parent folder or root list.
    if ($parent !== NULL) {
      if ($parent->isNameUnique($newName, (int) $item->id()) === FALSE) {
        throw new ValidationException(
          FolderShare::getStandardNameInUseExceptionMessage($newName));
      }
    }
    elseif (FolderShare::isRootNameUnique($newName, (int) $item->id()) === FALSE) {
      throw new ValidationException(
          FolderShare::getStandardNameInUseExceptionMessage($newName));
    }
 
    $this->parametersValidated = TRUE;
  }
 
  /*--------------------------------------------------------------------
   *
   * Configuration form setup.
   *
   *--------------------------------------------------------------------*/
 
  /**
   * {@inheritdoc}
   */
  public function hasConfigurationForm() {
    return TRUE;
  }
 
  /**
   * {@inheritdoc}
   */
  public function getDescription(bool $forPage) {
    $selectionIds = $this->getSelectionIds();
    if (empty($selectionIds) === TRUE) {
      $item = $this->getParent();
    }
    else {
      $item = FolderShare::load(reset($selectionIds));
    }
 
    $isShared = $item->getRootItem()->isAccessShared();
 
    if ($isShared === TRUE) {
      return [
        '',
        t('This item is shared. Changing its name may affect other users.'),
      ];
    }
 
    return [];
  }
 
  /**
   * {@inheritdoc}
   */
  public function getTitle(bool $forPage) {
    // The title varies for page vs. dialog:
    //
    // - Dialog: "Rename".
    //
    // - Page: "Rename NAME?" or "Rename shared NAME?".
    //   This follows Drupal convention.
    if ($forPage === FALSE) {
      return t('Rename');
    }
 
    $selectionIds = $this->getSelectionIds();
    if (empty($selectionIds) === TRUE) {
      $item = $this->getParent();
    }
    else {
      $item = FolderShare::load(reset($selectionIds));
    }
 
    $isShared = $item->getRootItem()->isAccessShared();
 
    if ($isShared === TRUE) {
      return t(
        'Rename shared "@name"?',
        [
          '@name' => $item->getName(),
        ]);
    }
 
    return t(
      'Rename shared "@name"?',
      [
        '@name' => $item->getName(),
      ]);
  }
 
  /**
   * {@inheritdoc}
   */
  public function getSubmitButtonName() {
    return t('Rename');
  }
 
  /*--------------------------------------------------------------------
   *
   * Configuration form.
   *
   *--------------------------------------------------------------------*/
 
  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(
    array $form,
    FormStateInterface $formState) {
 
    // Get the current item name to use as the form default value.
    $itemIds = $this->getSelectionIds();
    if (empty($itemIds) === TRUE) {
      $item = $this->getParent();
    }
    else {
      $item = FolderShare::load(reset($itemIds));
    }
 
    $this->configuration['name'] = $item->getName();
 
    // The command wrapper provides form basics:
    // - Attached libraries.
    // - Page title (if not an AJAX dialog).
    // - Description (from ::getDescription()).
    // - Submit buttion (labeled with ::getSubmitButtonName()).
    // - Cancel button (if AJAX dialog).
    //
    // Add a text field prompt for the new name.
    $form['rename'] = [
      '#type'          => 'textfield',
      '#name'          => 'rename',
      '#weight'        => 10,
      '#title'         => t('New name:'),
      '#size'          => 30,
      '#maxlength'     => 255,
      '#required'      => TRUE,
      '#default_value' => $this->configuration['name'],
      '#attributes'    => [
        'autofocus'    => 'autofocus',
        'spellcheck'   => 'false',
      ],
    ];
    $form['rename-description'] = [
      '#type'          => 'html_tag',
      '#name'          => 'rename-description',
      '#weight'        => 20,
      '#tag'           => 'p',
      '#value'         => t(
        'Enter a new name. Use any mix of characters except ":", "/", "\\".'),
      '#attributes'    => [
        'class'        => [
          'rename-description',
        ],
      ],
    ];
    $form['status'] = [
      '#type'          => 'status_messages',
      '#weight'        => 30,
    ];
 
    return $form;
  }
 
  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(
    array &$form,
    FormStateInterface $formState) {
 
    // Get the entered text for the item.
    $name = $formState->getValue('rename');
 
    // Validate the name alone, without considering file name extensions
    // or uniqueness.
    if (FolderShare::isNameLegal($name) === FALSE) {
      // Since the field is required, Drupal adds a default error message
      // when the field is left empty. Get rid of that so we can provide a
      // more helpful message.
      $formState->clearErrors();
 
      $formState->setErrorByName(
        'rename',
        strip_tags(
          (string) FolderShare::getStandardIllegalNameExceptionMessage($name)));
 
      $formState->setRebuild();
      return;
    }
 
    // Update the configuration.
    $this->configuration['name'] = $formState->getValue('rename');
 
    // Do a full validation.
    try {
      $this->validateParameters();
    }
    catch (RuntimeExceptionWithMarkup $e) {
      // Unfortunately, setErrorByName() will not accept complex markup,
      // such as for multi-line error messages. If we pass the markup,
      // the function strips it down to the last line of text. To avoid
      // this, we have to pass the message text instead.
      $formState->setErrorByName('rename', $e->getMessage());
      $formState->setRebuild();
    }
    catch (\Exception $e) {
      $formState->setErrorByName('rename', $e->getMessage());
      $formState->setRebuild();
    }
  }
 
  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(
    array &$form,
    FormStateInterface $formState) {
 
    if ($this->isValidated() === TRUE) {
      $this->execute();
    }
  }
 
  /*---------------------------------------------------------------------
   *
   * Execution behavior.
   *
   *---------------------------------------------------------------------*/
 
  /**
   * {@inheritdoc}
   */
  public function getExecuteBehavior() {
    if (empty($this->getSelectionIds()) === TRUE) {
      // When there is no selection, execution falls back to operating
      // on the current parent. After a change, the breadcrumbs or
      // other page decoration may differ. We need to refresh the page.
      return FolderShareCommandInterface::POST_EXECUTE_PAGE_REFRESH;
    }
 
    // When there is a selection, execution changes that selection on the
    // current page. While columns may change, the page doesn't, so we
    // only need to refresh the view.
    return FolderShareCommandInterface::POST_EXECUTE_VIEW_REFRESH;
  }
 
  /*--------------------------------------------------------------------
   *
   * Execute.
   *
   *--------------------------------------------------------------------*/
 
  /**
   * {@inheritdoc}
   */
  public function execute() {
    $itemIds = $this->getSelectionIds();
    if (empty($itemIds) === TRUE) {
      $item = $this->getParent();
    }
    else {
      $item = FolderShare::load(reset($itemIds));
    }
 
    try {
      $this->validateParameters();
      $item->rename($this->configuration['name']);
    }
    catch (RuntimeExceptionWithMarkup $e) {
      \Drupal::messenger()->addMessage($e->getMarkup(), 'error', TRUE);
    }
    catch (\Exception $e) {
      \Drupal::messenger()->addMessage($e->getMessage(), 'error');
    }
 
    if (Settings::getCommandNormalCompletionReportEnable() === TRUE) {
      \Drupal::messenger()->addMessage(
        t(
          "The @kind has been renamed.",
          [
            '@kind' => FolderShare::translateKind($item->getKind()),
          ]),
        'status');
    }
  }
 
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc