Passed
Branch feature/linting (138974)
by Christopher
02:18
created

ParagraphsEditorWidget::formElement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 15
nc 1
nop 5
dl 0
loc 23
ccs 0
cts 18
cp 0
crap 2
rs 9.0856
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\paragraphs_editor\Plugin\Field\FieldWidget;
4
5
use Drupal\Component\Utility\NestedArray;
0 ignored issues
show
Bug introduced by
The type Drupal\Component\Utility\NestedArray was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
0 ignored issues
show
Bug introduced by
The type Drupal\Core\Entity\Entit...playRepositoryInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Drupal\Core\Entity\RevisionableInterface;
0 ignored issues
show
Bug introduced by
The type Drupal\Core\Entity\RevisionableInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Drupal\Core\Field\FieldDefinitionInterface;
0 ignored issues
show
Bug introduced by
The type Drupal\Core\Field\FieldDefinitionInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use Drupal\Core\Field\FieldItemListInterface;
0 ignored issues
show
Bug introduced by
The type Drupal\Core\Field\FieldItemListInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Drupal\Core\Form\FormStateInterface;
0 ignored issues
show
Bug introduced by
The type Drupal\Core\Form\FormStateInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
0 ignored issues
show
Bug introduced by
The type Drupal\Core\Plugin\ContainerFactoryPluginInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Drupal\dom_processor\DomProcessor\DomProcessorInterface;
0 ignored issues
show
Bug introduced by
The type Drupal\dom_processor\Dom...r\DomProcessorInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Drupal\paragraphs\Plugin\Field\FieldWidget\InlineParagraphsWidget;
0 ignored issues
show
Bug introduced by
The type Drupal\paragraphs\Plugin...\InlineParagraphsWidget was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use Drupal\paragraphs_editor\EditorFieldValue\FieldValueManagerInterface;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Depend...tion\ContainerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
17
/**
18
 * Plugin implementation of the 'entity_reference_paragraphs_editor' widget.
19
 *
20
 * @FieldWidget(
21
 *   id = "entity_reference_paragraphs_editor",
22
 *   label = @Translation("Paragraphs (Editor)"),
23
 *   multiple_values = TRUE,
24
 *   description = @Translation("Editor paragraphs form widget."),
25
 *   field_types = {
26
 *     "entity_reference_revisions"
27
 *   }
28
 * )
29
 */
30
class ParagraphsEditorWidget extends InlineParagraphsWidget implements ContainerFactoryPluginInterface {
31
32
  /**
33
   * The editor field value manager for wrapping items.
34
   *
35
   * @var \Drupal\paragraphs_editor\EditorFieldValue\FieldValueManagerInterface
36
   */
37
  protected $fieldValueManager;
38
39
  /**
40
   * The dom processor for preparing and extracting editor content.
41
   *
42
   * @var \Drupal\dom_processor\DomProcessor\DomProcessorInterface
43
   */
44
  protected $domProcessor;
45
46
  /**
47
   * The plugin manager for bundle selector plugins.
48
   *
49
   * @var \Drupal\Component\Plugin\PluginManagerInterface
0 ignored issues
show
Bug introduced by
The type Drupal\Component\Plugin\PluginManagerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
50
   */
51
  protected $bundleSelectorManager;
52
53
  /**
54
   * The plugin manager for delivery plugins.
55
   *
56
   * @var \Drupal\Component\Plugin\PluginManagerInterface
57
   */
58
  protected $deliveryProviderManager;
59
60
  /**
61
   * The entity display repository service for getting view modes.
62
   *
63
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
64
   */
65
  protected $entityDisplayRepository;
66
67
  /**
68
   * Creates a paragraphs editor field widget.
69
   *
70
   * @param string $plugin_id
71
   *   The field widget plugin id.
72
   * @param mixed $plugin_definition
73
   *   The plugin definition.
74
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
75
   *   The paragraphs editor field definition.
76
   * @param array $settings
77
   *   The paragraphs editor field widget settings.
78
   * @param array $third_party_settings
79
   *   The third party settings for the widget.
80
   * @param \Drupal\paragraphs_editor\EditorFieldValue\FieldValueManagerInterface $field_value_manager
81
   *   The field value manager for getting and setting paragraphs editor field
82
   *   information.
83
   * @param \Drupal\dom_processor\DomProcessor\DomProcessorInterface $dom_processor
84
   *   The DOM processor for reading and writing markup.
85
   * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
86
   *   The view mode manager.
87
   * @param array $plugin_managers
88
   *   The paragraphs editor plugin managers.
89
   */
90
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, FieldValueManagerInterface $field_value_manager, DomProcessorInterface $dom_processor, EntityDisplayRepositoryInterface $entity_display_repository, array $plugin_managers) {
91
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
92
    $this->fieldValueManager = $field_value_manager;
93
    $this->domProcessor = $dom_processor;
94
    $this->entityDisplayRepository = $entity_display_repository;
95
    $this->bundleSelectorManager = $plugin_managers['bundle_selector'];
96
    $this->deliveryProviderManager = $plugin_managers['delivery_provider'];
97
  }
98
99
  /**
100
   * {@inheritdoc}
101
   */
102
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
103
    $plugin_managers = [];
104
    foreach ($container->getParameter('paragraphs_editor.plugin_managers') as $name => $def) {
105
      $plugin_managers[$name] = $container->get($def->id);
106
    }
107
    return new static(
108
      $plugin_id,
109
      $plugin_definition,
110
      $configuration['field_definition'],
111
      $configuration['settings'],
112
      $configuration['third_party_settings'],
113
      $container->get('paragraphs_editor.field_value.manager'),
114
      $container->get('dom_processor.dom_processor'),
115
      $container->get('entity_display.repository'),
116
      $plugin_managers
117
    );
118
  }
119
120
  /**
121
   * {@inheritdoc}
122
   */
123
  public static function defaultSettings() {
124
    return [
125
      'title' => t('Paragraph'),
0 ignored issues
show
Bug introduced by
The function t was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

125
      'title' => /** @scrutinizer ignore-call */ t('Paragraph'),
Loading history...
126
      'bundle_selector' => 'list',
127
      'delivery_provider' => 'modal',
128
      'filter_format' => 'paragraphs_ckeditor',
129
      'view_mode' => 'default',
130
      'prerender_count' => '10',
131
    ];
132
  }
133
134
  /**
135
   * {@inheritdoc}
136
   */
137
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
138
    $editable_data = $this->process('load', $items, $form_state);
139
140
    // Pretty much all the important parts are generated by the DOM processor.
141
    // Offloading things like '#attached' and '#attributes' to the processor
142
    // allows it to do things like dynamically load javascript for rendered
143
    // entities.
144
    return [
145
      'markup' => $element + [
146
        '#type' => 'text_format',
147
        '#format' => $editable_data->get('filter_format'),
148
        '#default_value' => $editable_data->get('markup'),
149
        '#rows' => 100,
150
        '#attributes' => $editable_data->get('attributes'),
151
        '#attached' => [
152
          'library' => $editable_data->get('libraries'),
153
          'drupalSettings' => $editable_data->get('drupalSettings'),
154
        ],
155
        '#allowed_formats' => [$editable_data->get('filter_format')],
156
      ],
157
      'context_id' => [
158
        '#type' => 'hidden',
159
        '#default_value' => $editable_data->get('context_id'),
160
      ],
161
    ];
162
  }
163
164
  /**
165
   * {@inheritdoc}
166
   */
167
  public function settingsForm(array $form, FormStateInterface $form_state) {
168
    $elements = [];
169
170
    $elements['title'] = [
171
      '#type' => 'textfield',
172
      '#title' => $this->t('Paragraph Title'),
173
      '#description' => $this->t('Label to appear as title on the button "Insert [title]. This label is translatable.'),
174
      '#default_value' => $this->getSetting('title'),
175
      '#required' => TRUE,
176
    ];
177
178
    $options = [];
179
    foreach ($this->bundleSelectorManager->getDefinitions() as $plugin) {
180
      $options[$plugin['id']] = $plugin['title'];
181
    }
182
183
    $elements['bundle_selector'] = [
184
      '#type' => 'select',
185
      '#title' => $this->t('Bundle Selection Handler'),
186
      '#description' => $this->t('The bundle selector form plugin that will be used to allow users to insert paragraph items.'),
187
      '#options' => $options,
188
      '#default_value' => $this->getSetting('bundle_selector'),
189
      '#required' => TRUE,
190
    ];
191
192
    $options = [];
193
    foreach ($this->deliveryProviderManager->getDefinitions() as $plugin) {
194
      $options[$plugin['id']] = $plugin['title'];
195
    }
196
197
    $elements['delivery_provider'] = [
198
      '#type' => 'select',
199
      '#title' => $this->t('Delivery Handler'),
200
      '#description' => $this->t('The delivery plugin that controls the user experience for how forms are delivered.'),
201
      '#options' => $options,
202
      '#default_value' => $this->getSetting('delivery_provider'),
203
      '#required' => TRUE,
204
    ];
205
206
    $options = [];
207
    foreach (filter_formats() as $filter_format) {
0 ignored issues
show
Bug introduced by
The function filter_formats was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

207
    foreach (/** @scrutinizer ignore-call */ filter_formats() as $filter_format) {
Loading history...
208
      $options[$filter_format->id()] = $filter_format->label();
209
    }
210
211
    $elements['filter_format'] = [
212
      '#type' => 'select',
213
      '#title' => 'Default Filter Format',
214
      '#description' => $this->t('The default filter format to use for the Editor instance.'),
215
      '#options' => $options,
216
      '#default_value' => $this->getSetting('filter_format'),
217
      '#required' => TRUE,
218
    ];
219
220
    $elements['view_mode'] = [
221
      '#type' => 'select',
222
      '#title' => 'Editor View Mode',
223
      '#description' => $this->t('The view mode that will be used to render embedded entities.'),
224
      '#options' => $this->entityDisplayRepository->getViewModeOptions('paragraph'),
225
      '#default_value' => $this->getSetting('prerender_count'),
226
      '#required' => TRUE,
227
    ];
228
229
    $options = [0 => $this->t('None')];
230
    for ($i = 5; $i <= 50; $i += 5) {
231
      $options[$i] = $i;
232
    }
233
    $options[-1] = $this->t('All');
234
    $elements['prerender_count'] = [
235
      '#type' => 'select',
236
      '#title' => 'Maximum Pre-Render Items',
237
      '#description' => $this->t("The maximum number of embedded paragraphs to render before an editor is initialized. Additional entities will be rendered via ajax on demand, and won't be available to edit until their respective ajax calls finish."),
238
      '#options' => $options,
239
      '#default_value' => $this->getSetting('prerender_count'),
240
      '#required' => TRUE,
241
    ];
242
243
    return $elements;
244
  }
245
246
  /**
247
   * {@inheritdoc}
248
   */
249
  public function settingsSummary() {
250
    $bundle_selector = $this->bundleSelectorManager->getDefinition($this->getSetting('bundle_selector'));
251
    $delivery_provider = $this->deliveryProviderManager->getDefinition($this->getSetting('delivery_provider'));
252
    $prerender_count = $this->getSetting('prerender_count');
253
    if ($prerender_count == '-1') {
254
      $prerender_count = 'All';
255
    }
256
    elseif ($prerender_count == '0') {
257
      $prerender_count = 'None';
258
    }
259
    $summary = [];
260
    $summary[] = $this->t('Title: @title', ['@title' => $this->getSetting('title')]);
261
    $summary[] = $this->t('Bundle Selector: @bundle_selector', ['@bundle_selector' => $bundle_selector['title']]);
262
    $summary[] = $this->t('Delivery Provider: @delivery_provider', ['@delivery_provider' => $delivery_provider['title']]);
263
    $summary[] = $this->t('Default Format: @filter_format', ['@filter_format' => $this->getSetting('filter_format')]);
264
    $summary[] = $this->t('View Mode: @mode', ['@mode' => $this->getSetting('view_mode')]);
265
    $summary[] = $this->t('Maximum Pre-Render Items: @prerender_count', ['@prerender_count' => $prerender_count]);
266
    return $summary;
267
  }
268
269
  /**
270
   * {@inheritdoc}
271
   */
272
  public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state) {
273
    $field_name = $this->fieldDefinition->getName();
274
    $path = array_merge($form['#parents'], [$field_name]);
275
    $values = NestedArray::getValue($form_state->getValues(), $path);
276
    $this->process('update', $items, $form_state, $values['markup']['format'], $values['markup']['value'], $values['context_id']);
277
  }
278
279
  /**
280
   * {@inheritdoc}
281
   */
282
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
283
    return \Drupal::service('paragraphs_editor.field_value.manager')->isParagraphsEditorField($field_definition);
284
  }
285
286
  /**
287
   * {@inheritdoc}
288
   */
289
  protected function mergeDefaults() {
290
    $this->settings += $this->fieldDefinition->getThirdPartySettings('paragraphs_editor');
291
    $this->settings += static::defaultSettings();
292
    $this->defaultSettingsMerged = TRUE;
0 ignored issues
show
Bug Best Practice introduced by
The property defaultSettingsMerged does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
293
  }
294
295
  /**
296
   * Passes markup through the paragraphs_editor DOM processor.
297
   *
298
   * @param string $variant
299
   *   The DOM Processor plugin variant to run:
300
   *     - 'load' is used to take saved markup and make it editable.
301
   *     - 'update' is used to take editor markup and make it saveable.
302
   * @param \Drupal\Core\Field\FieldItemListInterface $items
303
   *   The field items that will receive savable entities, or serve loadable
304
   *   entities. Note that neither of these operations perform entity saves.
305
   * @param \Drupal\Core\Form\FormStateInterface $form_state
306
   *   The form state for the form that the field widget belongs to.
307
   * @param string|null $format
308
   *   The default filter format name to apply to created text entities.
309
   * @param string|null $markup
310
   *   The markup to be processed. Defaults to the markup inside the text
311
   *   entity.
312
   * @param string|null $context_id
313
   *   The id of the root editing context to pull edits from.
314
   *
315
   * @see \Drupal\paragraphs_editor\Plugin\dom_processor\data_processor\ParagraphsEditorPreparer
316
   * @see \Drupal\paragraphs_editor\Plugin\dom_processor\data_processor\ParagraphsEditorDecorator
317
   * @see \Drupal\paragraphs_editor\Plugin\dom_processor\data_processor\ParagraphsEditorExtractor
318
   *
319
   * @return \Drupal\dom_processor\DomProcessor\DomProcessorResultInterface
0 ignored issues
show
Bug introduced by
The type Drupal\dom_processor\Dom...rocessorResultInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
320
   *   See the ParagraphsEditorDecorator and ParagraphsEditorExtractor DOM
321
   *   Processor plugins for more information.
322
   */
323
  protected function process($variant, FieldItemListInterface $items, FormStateInterface $form_state, $format = NULL, $markup = NULL, $context_id = NULL) {
324
    $field_value_wrapper = $this->fieldValueManager->wrapItems($items);
325
326
    if (!isset($markup)) {
327
      $markup = $field_value_wrapper->getMarkup();
328
    }
329
330
    if (!isset($format)) {
331
      $format = $field_value_wrapper->getFormat();
332
    }
333
334
    if (!$format) {
335
      $format = $this->getSetting('text_format');
336
    }
337
338
    // Check revisioning status.
339
    $entity = $form_state->getFormObject()->getEntity();
340
    $new_revision = FALSE;
341
    if ($entity instanceof RevisionableInterface) {
342
      if ($entity->isNewRevision()) {
343
        $new_revision = TRUE;
344
      }
345
      elseif ($entity->getEntityType()->hasKey('revision') && $form_state->getValue('revision')) {
346
        $new_revision = TRUE;
347
      }
348
    }
349
350
    return $this->domProcessor->process($markup, 'paragraphs_editor', $variant, [
351
      'field' => [
352
        'items' => $items,
353
        'context_id' => $context_id,
354
        'is_mutable' => TRUE,
355
        'wrapper' => $field_value_wrapper,
356
      ],
357
      'owner' => [
358
        'entity' => $entity,
359
        'new_revision' => $new_revision,
360
      ],
361
      'langcode' => $form_state->get('langcode'),
362
      'settings' => $this->getSettings(),
363
      'filter_format' => $format,
364
    ]);
365
  }
366
367
}
368