Completed
Push — 8.x-1.x ( 321310...2a7b34 )
by Janez
02:52
created

Upload::getForm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 12
Ratio 100 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 1
eloc 9
c 2
b 1
f 0
nc 1
nop 3
dl 12
loc 12
rs 9.4285
1
<?php
2
3
namespace Drupal\entity_browser\Plugin\EntityBrowser\Widget;
4
5
use Drupal\Component\Utility\NestedArray;
6
use Drupal\Core\Entity\EntityManagerInterface;
7
use Drupal\Core\Extension\ModuleHandlerInterface;
8
use Drupal\Core\Form\FormStateInterface;
9
use Drupal\Core\Utility\Token;
10
use Drupal\entity_browser\WidgetBase;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
13
14
/**
15
 * Uses a view to provide entity listing in a browser's widget.
16
 *
17
 * @EntityBrowserWidget(
18
 *   id = "upload",
19
 *   label = @Translation("Upload"),
20
 *   description = @Translation("Adds an upload field browser's widget.")
21
 * )
22
 */
23
class Upload extends WidgetBase {
24
25
  /**
26
   * The module handler service.
27
   *
28
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
29
   */
30
  protected $moduleHandler;
31
32
  /**
33
   * The token service.
34
   *
35
   * @var \Drupal\Core\Utility\Token
36
   */
37
  protected $token;
38
39
  /**
40
   * Constructs upload plugin.
41
   *
42
   * @param array $configuration
43
   *   A configuration array containing information about the plugin instance.
44
   * @param string $plugin_id
45
   *   The plugin_id for the plugin instance.
46
   * @param mixed $plugin_definition
47
   *   The plugin implementation definition.
48
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
49
   *   Event dispatcher service.
50
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
51
   *   The entity manager.
52
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
53
   *   The module handler.
54
   * @param \Drupal\Core\Utility\Token $token
55
   *   The token service.
56
   */
57
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, Token $token) {
58
    parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher, $entity_manager);
59
    $this->moduleHandler = $module_handler;
60
    $this->token = $token;
61
  }
62
63
  /**
64
   * {@inheritdoc}
65
   */
66
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
67
    return new static(
68
      $configuration,
69
      $plugin_id,
70
      $plugin_definition,
71
      $container->get('event_dispatcher'),
72
      $container->get('entity.manager'),
73
      $container->get('module_handler'),
74
      $container->get('token')
75
    );
76
  }
77
78
  /**
79
   * {@inheritdoc}
80
   */
81
  public function defaultConfiguration() {
82
    return [
83
      'upload_location' => 'public://',
84
    ] + parent::defaultConfiguration();
85
  }
86
87
  /**
88
   * {@inheritdoc}
89
   */
90 View Code Duplication
  public function getForm(array &$original_form, FormStateInterface $form_state, array $aditional_widget_parameters) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
91
    $form = [];
92
    $form['upload'] = [
93
      '#type' => 'managed_file',
94
      '#title' => t('Choose a file'),
95
      '#title_display' => 'invisible',
96
      '#upload_location' => $this->token->replace($this->configuration['upload_location']),
97
      '#multiple' => TRUE,
98
    ];
99
100
    return $form;
101
  }
102
103
  /**
104
   * {@inheritdoc}
105
   */
106
  public function validate(array &$form, FormStateInterface $form_state) {
107
    $uploaded_files = $form_state->getValue(['upload'], []);
108
    $trigger = $form_state->getTriggeringElement();
109
    // Only validate if we are uploading a file.
110
    if (empty($uploaded_files)  && $trigger['#value'] == 'Upload') {
111
      $form_state->setError($form['widget']['upload'], t('At least one file should be uploaded.'));
112
    }
113
  }
114
115
  /**
116
   * {@inheritdoc}
117
   */
118
  public function submit(array &$element, array &$form, FormStateInterface $form_state) {
119
    $files = $this->extractFiles($form_state);
120
    $this->selectEntities($files, $form_state);
121
    $this->clearFormValues($element, $form_state);
122
  }
123
124
  /**
125
   * Clear values from upload form element.
126
   *
127
   * @param array $element
128
   *   Upload form element.
129
   * @param \Drupal\Core\Form\FormStateInterface $form_state
130
   *   Form state object.
131
   */
132
  protected function clearFormValues(array &$element, FormStateInterface $form_state) {
133
    // We propagated entities to the other parts of the system. We can now remove
134
    // them from our values.
135
    $form_state->setValueForElement($element['upload']['fids'], '');
136
    NestedArray::setValue($form_state->getUserInput(), $element['upload']['fids']['#parents'], '');
137
  }
138
139
  /**
140
   * @param FormStateInterface $form_state
141
   *   Form state object.
142
   *
143
   * @return \Drupal\file\FileInterface[]
144
   *   Array of files.
145
   */
146
  protected function extractFiles(FormStateInterface $form_state) {
147
    $files = [];
148
    foreach ($form_state->getValue(['upload'], []) as $fid) {
149
      /** @var \Drupal\file\FileInterface $file */
150
      $file = $this->entityManager->getStorage('file')->load($fid);
151
      $file->setPermanent();
152
      $file->save();
153
      $files[] = $file;
154
    }
155
156
    return $files;
157
  }
158
159
  /**
160
   * {@inheritdoc}
161
   */
162
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
163
    $form['upload_location'] = [
164
      '#type' => 'textfield',
165
      '#title' => $this->t('Upload location'),
166
      '#default_value' => $this->configuration['upload_location'],
167
    ];
168
169
    if ($this->moduleHandler->moduleExists('token')) {
170
      $form['token_help'] = [
171
        '#theme' => 'token_tree_link',
172
        '#token_types' => ['file'],
173
      ];
174
      $form['upload_location']['#description'] = $this->t('You can use tokens in the upload location.');
175
    }
176
177
    return $form;
178
  }
179
180
}
181