Completed
Push — 8.x-1.x ( d50191...60fc6c )
by Janez
02:21
created

Upload::getForm()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 12
nc 2
nop 3
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\entity_browser\Plugin\EntityBrowser\Widget;
4
5
use Drupal\Component\Utility\NestedArray;
6
use Drupal\Core\Entity\EntityTypeManagerInterface;
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 Drupal\entity_browser\WidgetValidationManager;
12
use Drupal\file\FileInterface;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
15
16
/**
17
 * Uses a view to provide entity listing in a browser's widget.
18
 *
19
 * @EntityBrowserWidget(
20
 *   id = "upload",
21
 *   label = @Translation("Upload"),
22
 *   description = @Translation("Adds an upload field browser's widget.")
23
 * )
24
 */
25
class Upload extends WidgetBase {
26
27
  /**
28
   * The module handler service.
29
   *
30
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
31
   */
32
  protected $moduleHandler;
33
34
  /**
35
   * The token service.
36
   *
37
   * @var \Drupal\Core\Utility\Token
38
   */
39
  protected $token;
40
41
  /**
42
   * Upload constructor.
43
   *
44
   * @param array $configuration
45
   *   A configuration array containing information about the plugin instance.
46
   * @param string $plugin_id
47
   *   The plugin_id for the plugin instance.
48
   * @param mixed $plugin_definition
49
   *   The plugin implementation definition.
50
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
51
   *   Event dispatcher service.
52
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
53
   *   The entity type manager service.
54
   * @param \Drupal\entity_browser\WidgetValidationManager $validation_manager
55
   *   The Widget Validation Manager service.
56
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
57
   *   The module handler.
58
   * @param \Drupal\Core\Utility\Token $token
59
   *   The token service.
60
   */
61
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, EntityTypeManagerInterface $entity_type_manager, WidgetValidationManager $validation_manager, ModuleHandlerInterface $module_handler, Token $token) {
62
    parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher, $entity_type_manager, $validation_manager);
63
    $this->moduleHandler = $module_handler;
64
    $this->token = $token;
65
  }
66
67
  /**
68
   * {@inheritdoc}
69
   */
70 View Code Duplication
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
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...
71
    return new static(
72
      $configuration,
73
      $plugin_id,
74
      $plugin_definition,
75
      $container->get('event_dispatcher'),
76
      $container->get('entity_type.manager'),
77
      $container->get('plugin.manager.entity_browser.widget_validation'),
78
      $container->get('module_handler'),
79
      $container->get('token')
80
    );
81
  }
82
83
  /**
84
   * {@inheritdoc}
85
   */
86
  public function defaultConfiguration() {
87
    return [
88
      'upload_location' => 'public://',
89
      'multiple' => TRUE,
90
      'submit_text' => $this->t('Select files'),
91
      'extensions' => 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp',
92
    ] + parent::defaultConfiguration();
93
  }
94
95
  /**
96
   * {@inheritdoc}
97
   */
98
  public function getForm(array &$original_form, FormStateInterface $form_state, array $additional_widget_parameters) {
99
    $form = parent::getForm($original_form, $form_state, $additional_widget_parameters);
100
    $field_cardinality = $form_state->get(['entity_browser', 'validators', 'cardinality', 'cardinality']);
101
    $form['upload'] = [
102
      '#type' => 'managed_file',
103
      '#title' => $this->t('Choose a file'),
104
      '#title_display' => 'invisible',
105
      '#upload_location' => $this->token->replace($this->configuration['upload_location']),
106
      // Multiple uploads will only be accepted if the source field allows
107
      // more than one value.
108
      '#multiple' => $field_cardinality != 1 && $this->configuration['multiple'],
109
      '#upload_validators' => [
110
        'file_validate_extensions' => [$this->configuration['extensions']],
111
      ],
112
    ];
113
114
    return $form;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $form; (array<string,array>) is incompatible with the return type of the parent method Drupal\entity_browser\WidgetBase::getForm of type array<string,array<string,string|array>>.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
115
  }
116
117
  /**
118
   * {@inheritdoc}
119
   */
120
  protected function prepareEntities(array $form, FormStateInterface $form_state) {
121
    $files = [];
122
    foreach ($form_state->getValue(['upload'], []) as $fid) {
123
      $files[] = $this->entityTypeManager->getStorage('file')->load($fid);
124
    }
125
    return $files;
126
  }
127
128
  /**
129
   * {@inheritdoc}
130
   */
131
  public function submit(array &$element, array &$form, FormStateInterface $form_state) {
132
    if (!empty($form_state->getTriggeringElement()['#eb_widget_main_submit'])) {
133
      $files = $this->prepareEntities($form, $form_state);
134
      array_walk(
135
        $files,
136
        function (FileInterface $file) {
137
          $file->setPermanent();
138
          $file->save();
139
        }
140
      );
141
      $this->selectEntities($files, $form_state);
142
      $this->clearFormValues($element, $form_state);
143
    }
144
  }
145
146
  /**
147
   * Clear values from upload form element.
148
   *
149
   * @param array $element
150
   *   Upload form element.
151
   * @param \Drupal\Core\Form\FormStateInterface $form_state
152
   *   Form state object.
153
   */
154
  protected function clearFormValues(array &$element, FormStateInterface $form_state) {
155
    // We propagated entities to the other parts of the system. We can now remove
156
    // them from our values.
157
    $form_state->setValueForElement($element['upload']['fids'], '');
158
    NestedArray::setValue($form_state->getUserInput(), $element['upload']['fids']['#parents'], '');
159
  }
160
161
  /**
162
   * {@inheritdoc}
163
   */
164
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
165
    $form['upload_location'] = [
166
      '#type' => 'textfield',
167
      '#title' => $this->t('Upload location'),
168
      '#default_value' => $this->configuration['upload_location'],
169
    ];
170
    $form['multiple'] = [
171
      '#type' => 'checkbox',
172
      '#title' => $this->t('Accept multiple files'),
173
      '#default_value' => $this->configuration['multiple'],
174
      '#description' => $this->t('Multiple uploads will only be accepted if the source field allows more than one value.'),
175
    ];
176
    $form['extensions'] = [
177
      '#type' => 'textfield',
178
      '#title' => $this->t('Allowed file extensions'),
179
      '#description' => $this->t('Separate extensions with a space or comma and do not include the leading dot.'),
180
      '#default_value' => $this->configuration['extensions'],
181
      '#element_validate' => [[static::class, 'validateExtensions']],
182
      '#required' => TRUE,
183
    ];
184
185
    $form['submit_text'] = [
186
      '#type' => 'textfield',
187
      '#title' => $this->t('Submit button text'),
188
      '#default_value' => $this->configuration['submit_text'],
189
    ];
190
191
    if ($this->moduleHandler->moduleExists('token')) {
192
      $form['token_help'] = [
193
        '#theme' => 'token_tree_link',
194
        '#token_types' => ['file'],
195
      ];
196
      $form['upload_location']['#description'] = $this->t('You can use tokens in the upload location.');
197
    }
198
199
    return $form;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $form; (array<string,array>) is incompatible with the return type of the parent method Drupal\entity_browser\Wi...:buildConfigurationForm of type array<string,array>.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
200
  }
201
202
  /**
203
   * Validates a list of file extensions.
204
   *
205
   * @See \Drupal\file\Plugin\Field\FieldType\FileItem::validateExtensions
206
   */
207
  public static function validateExtensions($element, FormStateInterface $form_state) {
208
    if (!empty($element['#value'])) {
209
      $extensions = preg_replace('/([, ]+\.?)/', ' ', trim(strtolower($element['#value'])));
210
      $extensions = array_filter(explode(' ', $extensions));
211
      $extensions = implode(' ', array_unique($extensions));
212
      if (!preg_match('/^([a-z0-9]+([.][a-z0-9])* ?)+$/', $extensions)) {
213
        $form_state->setError($element, t('The list of allowed extensions is not valid, be sure to exclude leading dots and to separate extensions with a comma or space.'));
214
      }
215
      else {
216
        $form_state->setValueForElement($element, $extensions);
217
      }
218
    }
219
  }
220
221
}
222