Completed
Push — 8.x-1.x ( e0281d...3d2b6a )
by Janez
03:22
created

Upload::submit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 10
c 2
b 0
f 0
nc 2
nop 3
dl 0
loc 14
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\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
      'submit_text' => $this->t('Select files'),
90
    ] + parent::defaultConfiguration();
91
  }
92
93
  /**
94
   * {@inheritdoc}
95
   */
96
  public function getForm(array &$original_form, FormStateInterface $form_state, array $additional_widget_parameters) {
97
    $form = parent::getForm($original_form, $form_state, $additional_widget_parameters);
98
    $form['upload'] = [
99
      '#type' => 'managed_file',
100
      '#title' => t('Choose a file'),
101
      '#title_display' => 'invisible',
102
      '#upload_location' => $this->token->replace($this->configuration['upload_location']),
103
      '#multiple' => TRUE,
104
    ];
105
106
    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...
107
  }
108
109
  /**
110
   * {@inheritdoc}
111
   */
112
  protected function prepareEntities(array $form, FormStateInterface $form_state) {
113
    $files = [];
114
    foreach ($form_state->getValue(['upload'], []) as $fid) {
115
      $files[] = $this->entityTypeManager->getStorage('file')->load($fid);
116
    }
117
    return $files;
118
  }
119
120
  /**
121
   * {@inheritdoc}
122
   */
123
  public function submit(array &$element, array &$form, FormStateInterface $form_state) {
124
    if (!empty($form_state->getTriggeringElement()['#eb_widget_main_submit'])) {
125
      $files = $this->prepareEntities($form, $form_state);
126
      array_walk(
127
        $files,
128
        function (FileInterface $file) {
129
          $file->setPermanent();
130
          $file->save();
131
        }
132
      );
133
      $this->selectEntities($files, $form_state);
134
      $this->clearFormValues($element, $form_state);
135
    }
136
  }
137
138
  /**
139
   * Clear values from upload form element.
140
   *
141
   * @param array $element
142
   *   Upload form element.
143
   * @param \Drupal\Core\Form\FormStateInterface $form_state
144
   *   Form state object.
145
   */
146
  protected function clearFormValues(array &$element, FormStateInterface $form_state) {
147
    // We propagated entities to the other parts of the system. We can now remove
148
    // them from our values.
149
    $form_state->setValueForElement($element['upload']['fids'], '');
150
    NestedArray::setValue($form_state->getUserInput(), $element['upload']['fids']['#parents'], '');
151
  }
152
153
  /**
154
   * {@inheritdoc}
155
   */
156
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
157
    $form['upload_location'] = [
158
      '#type' => 'textfield',
159
      '#title' => $this->t('Upload location'),
160
      '#default_value' => $this->configuration['upload_location'],
161
    ];
162
163
    $form['submit_text'] = [
164
      '#type' => 'textfield',
165
      '#title' => $this->t('Submit button text'),
166
      '#default_value' => $this->configuration['submit_text'],
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;
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...
178
  }
179
180
}
181