Completed
Push — 8.x-1.x ( 9a9ef3...36f569 )
by Janez
02:25
created

Upload   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 166
Duplicated Lines 7.23 %

Coupling/Cohesion

Components 3
Dependencies 1

Importance

Changes 0
Metric Value
dl 12
loc 166
rs 10
c 0
b 0
f 0
wmc 12
lcom 3
cbo 1

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A create() 12 12 1
A defaultConfiguration() 0 7 1
A getForm() 0 15 2
A prepareEntities() 0 7 2
A submit() 0 14 2
A clearFormValues() 0 6 1
B buildConfigurationForm() 0 29 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
    ] + parent::defaultConfiguration();
92
  }
93
94
  /**
95
   * {@inheritdoc}
96
   */
97
  public function getForm(array &$original_form, FormStateInterface $form_state, array $additional_widget_parameters) {
98
    $form = parent::getForm($original_form, $form_state, $additional_widget_parameters);
99
    $field_cardinality = $form_state->get(['entity_browser', 'validators', 'cardinality', 'cardinality']);
100
    $form['upload'] = [
101
      '#type' => 'managed_file',
102
      '#title' => $this->t('Choose a file'),
103
      '#title_display' => 'invisible',
104
      '#upload_location' => $this->token->replace($this->configuration['upload_location']),
105
      // Multiple uploads will only be accepted if the source field allows
106
      // more than one value.
107
      '#multiple' => $field_cardinality != 1 && $this->configuration['multiple'],
108
    ];
109
110
    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...
111
  }
112
113
  /**
114
   * {@inheritdoc}
115
   */
116
  protected function prepareEntities(array $form, FormStateInterface $form_state) {
117
    $files = [];
118
    foreach ($form_state->getValue(['upload'], []) as $fid) {
119
      $files[] = $this->entityTypeManager->getStorage('file')->load($fid);
120
    }
121
    return $files;
122
  }
123
124
  /**
125
   * {@inheritdoc}
126
   */
127
  public function submit(array &$element, array &$form, FormStateInterface $form_state) {
128
    if (!empty($form_state->getTriggeringElement()['#eb_widget_main_submit'])) {
129
      $files = $this->prepareEntities($form, $form_state);
130
      array_walk(
131
        $files,
132
        function (FileInterface $file) {
133
          $file->setPermanent();
134
          $file->save();
135
        }
136
      );
137
      $this->selectEntities($files, $form_state);
138
      $this->clearFormValues($element, $form_state);
139
    }
140
  }
141
142
  /**
143
   * Clear values from upload form element.
144
   *
145
   * @param array $element
146
   *   Upload form element.
147
   * @param \Drupal\Core\Form\FormStateInterface $form_state
148
   *   Form state object.
149
   */
150
  protected function clearFormValues(array &$element, FormStateInterface $form_state) {
151
    // We propagated entities to the other parts of the system. We can now remove
152
    // them from our values.
153
    $form_state->setValueForElement($element['upload']['fids'], '');
154
    NestedArray::setValue($form_state->getUserInput(), $element['upload']['fids']['#parents'], '');
155
  }
156
157
  /**
158
   * {@inheritdoc}
159
   */
160
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
161
    $form['upload_location'] = [
162
      '#type' => 'textfield',
163
      '#title' => $this->t('Upload location'),
164
      '#default_value' => $this->configuration['upload_location'],
165
    ];
166
    $form['multiple'] = [
167
      '#type' => 'checkbox',
168
      '#title' => $this->t('Accept multiple files'),
169
      '#default_value' => $this->configuration['multiple'],
170
      '#description' => $this->t('Multiple uploads will only be accepted if the source field allows more than one value.'),
171
    ];
172
173
    $form['submit_text'] = [
174
      '#type' => 'textfield',
175
      '#title' => $this->t('Submit button text'),
176
      '#default_value' => $this->configuration['submit_text'],
177
    ];
178
179
    if ($this->moduleHandler->moduleExists('token')) {
180
      $form['token_help'] = [
181
        '#theme' => 'token_tree_link',
182
        '#token_types' => ['file'],
183
      ];
184
      $form['upload_location']['#description'] = $this->t('You can use tokens in the upload location.');
185
    }
186
187
    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...
188
  }
189
190
}
191