Completed
Push — 8.x-1.x ( 09a174...2d9790 )
by Janez
03:18
created

WidgetBase::getWeight()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Drupal\entity_browser;
4
5
use Drupal\Core\Entity\EntityTypeManagerInterface;
6
use Drupal\Core\Plugin\PluginBase;
7
use Drupal\Core\Form\FormStateInterface;
8
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
9
use Drupal\entity_browser\Events\EntitySelectionEvent;
10
use Drupal\entity_browser\Events\Events;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
13
use Symfony\Component\Validator\ConstraintViolationList;
14
15
/**
16
 * Base class for widget plugins.
17
 */
18
abstract class WidgetBase extends PluginBase implements WidgetInterface, ContainerFactoryPluginInterface {
19
20
  use PluginConfigurationFormTrait;
21
22
  /**
23
   * Plugin id.
24
   *
25
   * @var string
26
   */
27
  protected $id;
28
29
  /**
30
   * Plugin uuid.
31
   *
32
   * @var string
33
   */
34
  protected $uuid;
35
  /**
36
   * Plugin label.
37
   *
38
   * @var string
39
   */
40
  protected $label;
41
42
  /**
43
   * Plugin weight.
44
   *
45
   * @var int
46
   */
47
  protected $weight;
48
49
  /**
50
   * Event dispatcher service.
51
   *
52
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
53
   */
54
  protected $eventDispatcher;
55
56
  /**
57
   * Entity type manager service.
58
   *
59
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
60
   */
61
  protected $entityTypeManager;
62
63
  /**
64
   * The Widget Validation Manager service.
65
   *
66
   * @var \Drupal\entity_browser\WidgetValidationManager
67
   */
68
  protected $validationManager;
69
70
  /**
71
   * WidgetBase constructor.
72
   *
73
   * @param array $configuration
74
   *   A configuration array containing information about the plugin instance.
75
   * @param string $plugin_id
76
   *   The plugin_id for the plugin instance.
77
   * @param mixed $plugin_definition
78
   *   The plugin implementation definition.
79
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
80
   *   Event dispatcher service.
81
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
82
   *   The entity type manager service.
83
   * @param \Drupal\entity_browser\WidgetValidationManager $validation_manager
84
   *   The Widget Validation Manager service.
85
   */
86 View Code Duplication
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, EntityTypeManagerInterface $entity_type_manager, WidgetValidationManager $validation_manager) {
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...
87
    parent::__construct($configuration, $plugin_id, $plugin_definition);
88
    $this->eventDispatcher = $event_dispatcher;
89
    $this->entityTypeManager = $entity_type_manager;
90
    $this->validationManager = $validation_manager;
91
    $this->setConfiguration($configuration);
92
  }
93
94
  /**
95
   * {@inheritdoc}
96
   */
97 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...
98
    return new static(
99
      $configuration,
100
      $plugin_id,
101
      $plugin_definition,
102
      $container->get('event_dispatcher'),
103
      $container->get('entity_type.manager'),
104
      $container->get('plugin.manager.entity_browser.widget_validation')
105
    );
106
  }
107
108
  /**
109
   * {@inheritdoc}
110
   */
111
  public function defaultConfiguration() {
112
    return [];
113
  }
114
115
  /**
116
   * {@inheritdoc}
117
   */
118
  public function getConfiguration() {
119
    return [
120
      'settings' => array_diff_key(
121
        $this->configuration,
122
        ['entity_browser_id' => 0]
123
      ),
124
      'uuid' => $this->uuid(),
125
      'weight' => $this->getWeight(),
126
      'label' => $this->label(),
127
      'id' => $this->id(),
128
    ];
129
  }
130
131
  /**
132
   * {@inheritdoc}
133
   */
134
  public function setConfiguration(array $configuration) {
135
    $configuration += [
136
      'settings' => [],
137
      'uuid' => '',
138
      'weight' => '',
139
      'label' => '',
140
      'id' => '',
141
    ];
142
143
    $this->configuration = $configuration['settings'] + $this->defaultConfiguration();
144
    $this->label = $configuration['label'];
145
    $this->weight = $configuration['weight'];
146
    $this->uuid = $configuration['uuid'];
147
    $this->id = $configuration['id'];
148
  }
149
150
  /**
151
   * {@inheritdoc}
152
   */
153
  public function calculateDependencies() {
154
    return [];
155
  }
156
157
  /**
158
   * {@inheritdoc}
159
   */
160
  public function id() {
161
    return $this->id;
162
  }
163
164
  /**
165
   * {@inheritdoc}
166
   */
167
  public function uuid() {
168
    return $this->uuid;
169
  }
170
171
  /**
172
   * {@inheritdoc}
173
   */
174
  public function label() {
175
    return $this->label;
176
  }
177
178
  /**
179
   * {@inheritdoc}
180
   */
181
  public function setLabel($label) {
182
    $this->label = $label;
183
    return $this;
184
  }
185
186
  /**
187
   * {@inheritdoc}
188
   */
189
  public function getWeight() {
190
    return $this->weight;
191
  }
192
193
  /**
194
   * {@inheritdoc}
195
   */
196
  public function setWeight($weight) {
197
    $this->weight = $weight;
198
    return $this;
199
  }
200
201
  /**
202
   * {@inheritdoc}
203
   */
204
  public function getForm(array &$original_form, FormStateInterface $form_state, array $additional_widget_parameters) {
205
    // Allow configuration overrides at runtime based on form state to enable
206
    // use cases where the instance of a widget may have contextual
207
    // configuration like field settings. "widget_context" doesn't have to be
208
    // used in this way, if a widget doesn't want its default configuration
209
    // overwritten it can not call this method and implement its own logic.
210
    foreach ($this->defaultConfiguration() as $key => $value) {
211
      if ($form_state->has(['entity_browser', 'widget_context', $key]) && isset($this->configuration[$key])) {
212
        $this->configuration[$key] = $form_state->get(['entity_browser', 'widget_context', $key]);
213
      }
214
    }
215
    // Do not make assumptions about how the widget is rendered.
216
    return [];
217
  }
218
219
  /**
220
   * Prepares the entities without saving them.
221
   *
222
   * We need this method when we want to validate or perform other operations
223
   * before submit.
224
   *
225
   * @param array $form
226
   *   Complete form.
227
   * @param \Drupal\Core\Form\FormStateInterface $form_state
228
   *   The form state object.
229
   *
230
   * @return \Drupal\Core\Entity\EntityInterface[]
231
   *   Array of entities.
232
   */
233
  abstract protected function prepareEntities(array $form, FormStateInterface $form_state);
234
235
  /**
236
   * {@inheritdoc}
237
   */
238
  public function validate(array &$form, FormStateInterface $form_state) {
239
    $entities = $this->prepareEntities($form, $form_state);
240
    $validators = $form_state->get(['entity_browser', 'validators']);
241
    if ($validators) {
242
      $violations = $this->runWidgetValidators($entities, $validators);
243
      foreach ($violations as $violation) {
244
        $form_state->setError($form['widget'], $violation->getMessage());
245
      }
246
    }
247
  }
248
249
  /**
250
   * Run widget validators.
251
   *
252
   * @param array $entities
253
   *   Array of entity ids to validate.
254
   * @param array $validators
255
   *   Array of widget validator ids.
256
   *
257
   * @return \Symfony\Component\Validator\ConstraintViolationListInterface
258
   *   A list of constraint violations. If the list is empty, validation
259
   *   succeeded.
260
   */
261
  protected function runWidgetValidators(array $entities, $validators = []) {
262
    $violations = new ConstraintViolationList();
263
    foreach ($validators as $validator_id => $options) {
264
      /** @var \Drupal\entity_browser\WidgetValidationInterface $widget_validator */
265
      $widget_validator = $this->validationManager->createInstance($validator_id, []);
266
      if ($widget_validator) {
267
        $violations->addAll($widget_validator->validate($entities, $options));
268
      }
269
    }
270
271
    return $violations;
272
  }
273
274
  /**
275
   * {@inheritdoc}
276
   */
277
  public function submit(array &$element, array &$form, FormStateInterface $form_state) {}
278
279
  /**
280
   * Dispatches event that informs all subscribers about new selected entities.
281
   *
282
   * @param array $entities
283
   *   Array of entities.
284
   */
285
  protected function selectEntities(array $entities, FormStateInterface $form_state) {
286
    $selected_entities = &$form_state->get(['entity_browser', 'selected_entities']);
287
    $selected_entities = array_merge($selected_entities, $entities);
288
289
    $this->eventDispatcher->dispatch(
290
      Events::SELECTED,
291
      new EntitySelectionEvent(
292
        $this->configuration['entity_browser_id'],
293
        $form_state->get(['entity_browser', 'instance_uuid']),
294
        $entities
295
      ));
296
  }
297
298
}
299