GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — 8.x-4.x ( 4424ac...1a3975 )
by Kevin
05:00
created

_layout_builder_block_form_alter()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 58
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 43
nc 3
nop 2
dl 0
loc 58
rs 8.2986
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @file
5
 * Contains df_tools_blocks.module.
6
 */
7
8
use Drupal\block_content\Entity\BlockContent;
9
use Drupal\block_content\Entity\BlockContentType;
10
use Drupal\Component\Utility\Html;
11
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
12
use Drupal\Core\Entity\EntityInterface;
13
use Drupal\Core\Entity\FieldableEntityInterface;
14
use Drupal\Core\Form\FormStateInterface;
15
use Drupal\Core\Render\Element;
16
use Drupal\Core\StringTranslation\TranslatableMarkup;
17
use Drupal\field\Entity\FieldConfig;
18
19
/**
20
 * Implements hook_modules_installed().
21
 */
22
function df_tools_blocks_modules_installed(array $modules) {
23
  // Don't do anything during config sync.
24
  if (\Drupal::isConfigSyncing()) {
25
    return;
26
  }
27
28
  // Add support for Acquia DAM Asset media entities to the Media field if the
29
  // df_tools_media_acquiadam module is installed.
30
  if (in_array('df_tools_media_acquiadam', $modules)) {
31
    // Retrieve the block's 'media' field.
32
    $instance = FieldConfig::loadByName('block_content', 'media', 'field_media');
33
34
    // Add 'acquia_dam_asset' to the list of allowed target bundles.
35
    $settings = $instance->getSetting('handler_settings');
36
    $settings['target_bundles'][] = 'acquia_dam_asset';
37
    $instance->setSetting('handler_settings', $settings);
38
    $instance->save();
39
  }
40
}
41
42
/**
43
 * Implements hook_ENTITY_TYPE_view_alter().
44
 */
45
function df_tools_blocks_block_content_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
46
  if ($entity->bundle() === 'basic') {
47
    $wrapper = [
48
      '#prefix' => '<div class="full-width-inner">',
49
      '#suffix' => '</div>',
50
      '#type' => 'container',
51
      '#weight' => -1,
52
      '#attributes' => [
53
        'class' => ['basic-block-fields'],
54
      ],
55
    ];
56
    $build['wrapper'] = $wrapper;
57
    $build['#prefix'] = '<div class="basic-block">';
58
    $build['#suffix'] = '</div>';
59
  }
60
61
  if ($entity->bundle() === 'hero') {
62
63
    $hero_alignment = $entity->get('field_hero_alignment')->getString();
0 ignored issues
show
Bug introduced by
The method get() does not exist on Drupal\Core\Entity\EntityInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Drupal\Core\Entity\EntityChangedInterface or Drupal\Core\Entity\RevisionableInterface or Drupal\Core\Entity\EntityBase or Drupal\Core\Entity\EntityPublishedInterface or Drupal\Core\Entity\TranslatableInterface or Drupal\Core\Entity\SynchronizableInterface or Drupal\Tests\Core\Entity...rageTestEntityInterface or Drupal\Core\Entity\EntityDescriptionInterface or Drupal\Core\Entity\Entit...uginCollectionInterface or Drupal\Core\Entity\RevisionLogInterface or Drupal\Core\Entity\Trans...leRevisionableInterface or Drupal\Tests\Core\Entity\RevisionableEntity or Drupal\Core\Entity\Entity or Drupal\Tests\Core\Entity\SimpleTestEntity or Drupal\Tests\content_mod...n\Unit\SimpleTestEntity or Drupal\Tests\Core\Entity\RevisionableEntity or Drupal\Core\Entity\Trans...leRevisionableInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

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

63
    $hero_alignment = $entity->/** @scrutinizer ignore-call */ get('field_hero_alignment')->getString();
Loading history...
64
    if (preg_match('/^[a-z_]+$/i', $hero_alignment)) {
65
      switch ($hero_alignment) {
66
        case 'center':
67
          $hero_alignment = 'justify-content-center';
68
          break;
69
        case 'right':
70
          $hero_alignment = 'justify-content-end';
71
          break;
72
        default:
73
          $hero_alignment = 'justify-content-start';
74
          break;
75
      }
76
    }
77
78
    $hero_callout_width = $entity->get('field_callout_width')->getString();
79
    switch($hero_callout_width) {
80
      case '03':
81
        $hero_callout_width = 'col col-md-5 col-lg-3';
82
        break;
83
      case '04':
84
        $hero_callout_width = 'col col-md-6 col-lg-4';
85
        break;
86
      case '05':
87
        $hero_callout_width = 'col col-md-7 col-lg-5';
88
        break;
89
      case '06':
90
        $hero_callout_width = 'col col-md-8 col-lg-6';
91
        break;
92
      case '07':
93
        $hero_callout_width = 'col col-md-9 col-lg-7';
94
        break;
95
      case '08':
96
        $hero_callout_width = 'col col-md-10 col-lg-8';
97
        break;
98
      case '09':
99
        $hero_callout_width = 'col col-md-11 col-lg-9';
100
        break;
101
      case '10':
102
        $hero_callout_width = 'col col-md-12 col-lg-10';
103
        break;
104
      case '11':
105
        $hero_callout_width = 'col col-md-12 col-lg-11';
106
        break;
107
      case '12':
108
        $hero_callout_width = 'col-12';
109
        break;
110
    }
111
112
    $wrapper = [
113
      '#prefix' => '<div class="container"><div class="row ' . $hero_alignment . '">',
114
      '#suffix' => '</div></div>',
115
      '#type' => 'container',
116
      '#weight' => -1,
117
      '#attributes' => [
118
        'class' => ['hero-block-fields', $hero_callout_width ],
119
      ],
120
      '#children' => [],
121
    ];
122
    foreach (Element::getVisibleChildren($build) as $field_name) {
123
      if ($field_name === 'field_icon' && isset($build[$field_name]['#object'])) {
124
        $icon = $build[$field_name]['#object']->field_icon->getString();
125
        if (!empty($icon)) {
126
          $wrapper['#children'][$field_name] = [
127
            '#markup' => '<i class="fa ' . $icon . ' hero-icon"></i>',
128
            '#allowed_tags' => ['i'],
129
          ];
130
        }
131
        unset($build[$field_name]);
132
      }
133
      elseif ($field_name !== 'field_hero_background') {
134
        $wrapper['#children'][$field_name] = $build[$field_name];
135
        unset($build[$field_name]);
136
      }
137
    }
138
139
    $hero_first_line_size = $entity->get('field_first_line_size')->getString();
140
    $wrapper['#children']['field_first_line']['#attributes']['class'][] = 'size-' . $hero_first_line_size;
141
142
    $hero_second_line_size = $entity->get('field_second_line_size')->getString();
143
    $wrapper['#children']['field_second_line']['#attributes']['class'][] = 'size-' . $hero_second_line_size;
144
145
    // Attach styles.
146
    $alignment = $entity->get('field_hero_alignment')->getString();
147
    if (preg_match('/^[a-z_]+$/i', $alignment)) {
148
      $wrapper['#attributes']['class'][] = Html::cleanCssIdentifier('hero-block-align-' . $alignment);
149
    }
150
    $color_regex = '/^#[0-9a-f]{6}$/i';
151
    $callout_background_color = $entity->get('field_callout_background_color')->getString();
152
    $callout_background_opacity = $entity->get('field_callout_background_opacity')->getString();
153
    $hex = trim($callout_background_color, '#');
154
    $r = hexdec(substr($hex, 0, 2));
155
    $g = hexdec(substr($hex, 2, 2));
156
    $b = hexdec(substr($hex, 4, 2));
157
    $callout_background_color = "background-color: rgba($r,$g,$b,$callout_background_opacity)";
158
    $wrapper['#attributes']['style'] = $callout_background_color;
159
    $text_color = $entity->get('field_text_color')->getString();
160
    if (preg_match($color_regex, $text_color)) {
161
      $wrapper['#children']['field_first_line']['#attributes']['style'] = 'color: ' . $text_color;
162
      $wrapper['#children']['field_second_line']['#attributes']['style'] = 'color: ' . $text_color;
163
    }
164
    $gradient_color = $entity->get('field_gradient_color')->getString();
165
    if (preg_match($color_regex, $gradient_color)) {
166
      switch ($alignment) {
167
        case 'left':
168
          $direction = 'to right';
169
          break;
170
171
        case 'right':
172
          $direction = 'to left';
173
          break;
174
175
        default:
176
          $direction = 'to bottom';
177
          break;
178
      }
179
      $build['field_hero_background']['#attributes']['style'] = "background-image: linear-gradient($direction, $gradient_color, transparent)";
180
    }
181
    $callout_color = $entity->get('field_callout_color')->getString();
182
    if (preg_match($color_regex, $callout_color)) {
183
      $style = 'background-color: ' . $callout_color . ';';
184
      $hex = trim($callout_color, '#');
185
      $r = hexdec(substr($hex, 0, 2));
186
      $g = hexdec(substr($hex, 2, 2));
187
      $b = hexdec(substr($hex, 4, 2));
188
      if ($r + $g + $b > 382) {
189
        $wrapper['#children']['field_hero_link'][0]['#attributes']['class'][] = 'hero-link-light-bg';
190
        $style .= 'border-color:black;color:black;';
191
      }
192
      else {
193
        $wrapper['#children']['field_hero_link'][0]['#attributes']['class'][] = 'hero-link-dark-bg';
194
        $style .= 'border-color:white;color:white;';
195
      }
196
      $wrapper['#children']['field_hero_link'][0]['#attributes']['style'] = $style;
197
    }
198
    $wrapper['#attached']['library'][] = 'df_tools_blocks/hero';
199
    $build['wrapper'] = $wrapper;
200
    $build['#prefix'] = '<div class="hero-block">';
201
    $build['#suffix'] = '</div>';
202
  }
203
  if ($entity->bundle() === 'video_hero') {
204
    $wrapper = [
205
      '#type' => 'container',
206
      '#weight' => -1,
207
      '#attributes' => [
208
        'class' => ['video-hero-block-fields'],
209
      ],
210
      '#children' => [],
211
    ];
212
    foreach (Element::getVisibleChildren($build) as $field_name) {
213
      if ($field_name === 'field_hero_link') {
214
        $build[$field_name]['#attributes']['class'][] = 'button';
215
      }
216
      if ($field_name !== 'field_media') {
217
        $wrapper['#children'][$field_name] = $build[$field_name];
218
        unset($build[$field_name]);
219
      }
220
    }
221
    $build['wrapper'] = $wrapper;
222
    $build['#attributes']['class'][] = 'video-hero-block';
223
    $build['#attributes']['class'][] = 'full-width-row';
224
    $build['#attached']['library'][] = 'df_tools_blocks/video_hero';
225
  }
226
}
227
228
/**
229
 * Implements hook_theme_suggestions_HOOK_alter().
230
 */
231
function df_tools_blocks_theme_suggestions_block_alter(array &$suggestions, array $variables) {
232
  // Add block--block-content--bundle.html.twig suggestions.
233
  if (isset($variables['elements']['content']) && isset($variables['elements']['content']['#block_content'])) {
234
    /** @var \Drupal\block_content\Entity\BlockContent $entity */
235
    $entity = $variables['elements']['content']['#block_content'];
236
    $suggestions[] = 'block__block_content__' . $entity->bundle();
237
  }
238
}
239
240
/**
241
 * Implements hook_form_alter().
242
 */
243
function df_tools_blocks_form_alter(&$form, FormStateInterface $form_state, $form_id) {
244
  if (preg_match('/^block_content.*panels_ipe_form$/', $form_id)) {
245
    // Wrap the revision information and any other vertical tabs in a fieldset.
246
    // This breaks vertical tab styling, but we don't want this open most of
247
    // the time anyway.
248
    $form['advanced'] = [
249
      '#type' => 'details',
250
      '#title' => t('Advanced'),
251
      '#collapsed' => TRUE,
252
      '#attributes' => ['class' => ['fieldset']],
253
      '#weight' => 100,
254
      0 => $form['advanced'],
255
    ];
256
257
    // Hide the Block description description and remove any mention of "Block".
258
    $form['info']['widget'][0]['value']['#title'] = t('Description');
259
    $form['info']['widget'][0]['value']['#description'] = [];
260
  }
261
262
  if (preg_match('/^block_content_\X*_edit_form$/', $form_id)) {
263
    // Add a 'copy' button to all custom blocks edit forms.
264
    $form['actions']['copy'] = [
265
      '#type' => 'submit',
266
      '#value' => t('Copy'),
267
      '#submit' => ['df_tools_blocks_block_content_replicate'],
268
      '#weight' => 9,
269
    ];
270
  }
271
  // Add a callback to #process to the layout_builder_update_block and
272
  // layout_builder_add_block. drupal.org/node/3028391
273
  $form_ids = ['layout_builder_update_block', 'layout_builder_add_block'];
274
  if (!in_array($form_id, $form_ids)) {
275
    return;
276
  }
277
  $form['settings']['block_form']['#process'][] = '_layout_builder_block_form_alter';
278
}
279
280
/**
281
 * Process callback for layout_builder block form.
282
 *
283
 */
284
function _layout_builder_block_form_alter(array $element, FormStateInterface $form_state) {
285
286
  if (isset($element['field_hero_background'])) {
287
    // Move the hero image out of the details element and set a better label.
288
    $element['field_hero_background']['widget']['#type'] = 'container';
289
    $element['field_hero_background']['widget']['entity_browser']['#process'][] = '_df_tools_blocks_hero_browser_button';
290
     // Remove the link fieldset and put the URI and title side-by-side.
291
    $element['field_hero_link']['widget'][0]['#type'] = 'container';
292
    $element['field_hero_link']['widget'][0]['#attributes']['class'][] = 'row';
293
    unset($element['field_hero_link']['widget'][0]['uri']['#description']);
294
    $element['field_hero_link']['widget'][0]['uri']['#title'] = t('Callout link');
295
    $element['field_hero_link']['widget'][0]['title']['#title'] = t('Callout text');
296
    if (\Drupal::moduleHandler()->moduleExists('layout_builder_modal')) {
297
      $element['field_hero_link']['widget'][0]['uri']['#prefix'] = '<div class="col-6">';
298
      $element['field_hero_link']['widget'][0]['uri']['#suffix'] = '</div>';
299
      $element['field_hero_link']['widget'][0]['title']['#prefix'] = '<div class="col-6">';
300
      $element['field_hero_link']['widget'][0]['title']['#suffix'] = '</div>';
301
    }
302
    else {
303
      $element['field_hero_link']['widget'][0]['uri']['#prefix'] = '<div class="col-12">';
304
      $element['field_hero_link']['widget'][0]['uri']['#suffix'] = '</div>';
305
      $element['field_hero_link']['widget'][0]['title']['#prefix'] = '<div class="col-12">';
306
      $element['field_hero_link']['widget'][0]['title']['#suffix'] = '</div>';
307
    }
308
309
    $style_fields = [
310
      'field_text_color',
311
      'field_first_line_size',
312
      'field_second_line_size',
313
      'field_gradient_color',
314
      'field_callout_color',
315
      'field_callout_width',
316
      'field_callout_background_color',
317
      'field_callout_background_opacity',
318
      'field_hero_alignment',
319
    ];
320
    $element['style_fields'] = [
321
      '#type' => 'details',
322
      '#title' => t('Advanced settings'),
323
      '#weight' => 2,
324
    ];
325
326
    foreach ($style_fields as $field) {
327
      if ((strpos($field, 'color') !== FALSE) && isset($element[$field])) {
328
          $element[$field]['widget'][0]['value']['#type'] = 'color';
329
      }
330
      if (\Drupal::moduleHandler()->moduleExists('layout_builder_modal')) {
331
        $element[$field]['#attributes']['class'][] = 'col-4';
332
      }
333
      else {
334
        $element[$field]['#attributes']['class'][] = 'col-6';
335
      }
336
      $element['style_fields'][] = $element[$field];
337
      $element['style_fields']['#weight'] = $element[$field]['#weight'];
338
      unset($element[$field]);
339
    }
340
  }
341
  return $element;
342
}
343
344
/**
345
 * Implements hook_form_FORM_ID_alter().
346
 */
347
function df_tools_blocks_form_panels_ipe_block_plugin_form_alter(&$form, FormStateInterface $form_state, $form_id) {
348
  // Modify the block placement form.
349
  if (isset($form['flipper']['front']['settings']['admin_label'])) {
350
    $form['flipper']['front']['settings']['admin_label']['#weight'] = -2;
351
  }
352
353
  if (isset($form['flipper']['front']['settings']['label_display'])) {
354
    if (empty($form['uuid']['#value'])) {
355
      $form['flipper']['front']['settings']['label_display']['#default_value'] = FALSE;
356
    }
357
    $form['flipper']['front']['settings']['label_display']['#weight'] = -1;
358
  }
359
360
  if (isset($form['flipper']['front']['settings']['label'])) {
361
    $form['flipper']['front']['settings']['label']['#weight'] = 0;
362
    $form['flipper']['front']['settings']['label']['#states'] = [
363
      'visible' => [
364
        ':input[name="settings[label_display]"]' => ['checked' => TRUE],
365
      ],
366
    ];
367
  }
368
369
  // Add special logic for the Entity Browser block plugins.
370
  if (isset($form['plugin_id'])) {
371
    if ($form['plugin_id']['#value'] === 'content_embed') {
372
      // Only auto-open the Content Embed block if it is empty.
373
      if (empty(Element::getVisibleChildren($form['flipper']['front']['settings']['selection']['table'])) && !$form_state->isProcessingInput()) {
374
        $form['#attached']['library'][] = 'df_tools_blocks/auto_open';
375
        $form['#attributes']['data-df-tools-blocks-auto-open'] = 'settings_selection_nids_entity_browser';
376
      }
377
378
      // Modify the Content Embed form to guide users to valid View Modes.
379
      if (empty($form['flipper']['front']['settings']['view_mode']['#default_value'])) {
380
        $form['flipper']['front']['settings']['view_mode']['#default_value'] = 'featured';
381
      }
382
      $excluded_modes = [
383
        'basic_info',
384
        'content_browser',
385
        'rss',
386
        'search_index',
387
        'search_result',
388
        'token',
389
        'full',
390
        'df',
391
      ];
392
      foreach ($excluded_modes as $view_mode) {
393
        if (isset($form['flipper']['front']['settings']['view_mode']['#options'][$view_mode])) {
394
          unset($form['flipper']['front']['settings']['view_mode']['#options'][$view_mode]);
395
        }
396
      }
397
    }
398
    elseif ($form['plugin_id']['#value'] === 'media_embed') {
399
      if (empty(Element::getVisibleChildren($form['flipper']['front']['settings']['selection']['table'])) && !$form_state->isProcessingInput()) {
400
        $form['#attached']['library'][] = 'df_tools_blocks/auto_open';
401
        $form['#attributes']['data-df-tools-blocks-auto-open'] = 'settings_selection_mids_entity_browser';
402
      }
403
      $excluded_modes = [
404
        'media_browser',
405
        'product_slideshow_thumbnail',
406
        'hero_thin',
407
        'hero_product',
408
        'embedded',
409
        'token',
410
      ];
411
      foreach ($excluded_modes as $view_mode) {
412
        if (isset($form['flipper']['front']['settings']['view_mode']['#options'][$view_mode])) {
413
          unset($form['flipper']['front']['settings']['view_mode']['#options'][$view_mode]);
414
        }
415
      }
416
    }
417
  }
418
}
419
420
/**
421
 * Implements hook_form_FORM_ID_alter().
422
 */
423
function df_tools_blocks_form_block_content_hero_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
424
  df_tools_blocks_form_block_content_hero_panels_ipe_form_alter($form, $form_state, $form_id);
425
}
426
427
/**
428
 * Implements hook_form_FORM_ID_alter().
429
 */
430
function df_tools_blocks_form_block_content_hero_panels_ipe_form_alter(&$form, FormStateInterface $form_state, $form_id) {
431
  // Move the hero image out of the details element and set a better label.
432
  $form['field_hero_background']['widget']['#type'] = 'container';
433
  $form['field_hero_background']['widget']['entity_browser']['#process'][] = '_df_tools_blocks_hero_browser_button';
434
  // Remove the link fieldset and put the URI and title side-by-side.
435
  $form['field_hero_link']['widget'][0]['#type'] = 'container';
436
  $form['field_hero_link']['widget'][0]['#attributes']['class'][] = 'row';
437
  unset($form['field_hero_link']['widget'][0]['uri']['#description']);
438
  $form['field_hero_link']['widget'][0]['uri']['#title'] = t('Callout link');
439
  $form['field_hero_link']['widget'][0]['title']['#title'] = t('Callout text');
440
  $form['field_hero_link']['widget'][0]['uri']['#prefix'] = '<div class="large-6 columns">';
441
  $form['field_hero_link']['widget'][0]['uri']['#suffix'] = '</div>';
442
  $form['field_hero_link']['widget'][0]['title']['#prefix'] = '<div class="large-6 columns">';
443
  $form['field_hero_link']['widget'][0]['title']['#suffix'] = '</div>';
444
  // Group complex form elements into the advanced section.
445
  $form['field_icon']['#attributes']['class'][] = 'visually-hidden';
446
  $form['field_nested_block']['#attributes']['class'][] = 'visually-hidden';
447
  $style_fields = [
448
    'field_text_color',
449
    'field_gradient_color',
450
    'field_callout_color',
451
    'field_callout_background_color',
452
  ];
453
  $form['style_fields'] = [
454
    '#type' => 'container',
455
    '#attributes' => ['class' => ['row']],
456
  ];
457
  foreach ($style_fields as $field) {
458
    if (strpos($field, 'color') !== FALSE) {
459
      $form[$field]['widget'][0]['value']['#type'] = 'color';
460
    }
461
    $form[$field]['#attributes']['class'][] = 'large-4 columns';
462
    $form['style_fields'][] = $form[$field];
463
    $form['style_fields']['#weight'] = $form[$field]['#weight'];
464
    unset($form[$field]);
465
  }
466
}
467
468
/**
469
 * Does nit-picky changes on the Hero image entity browser.
470
 *
471
 * @param array $element
472
 *   The element render array.
473
 *
474
 * @return array
475
 *   The possibly modified form render array.
476
 */
477
function _df_tools_blocks_hero_browser_button(array $element) {
478
  $element['entity_browser']['open_modal']['#value'] = t('Select background');
479
  if (isset($element['entity_browser']['open_modal']['#ajax'])) {
480
    /** @var \Drupal\entity_browser\DisplayInterface $display */
481
    $display = $element['entity_browser']['open_modal']['#ajax']['callback'][0];
482
    $configuration = $display->getConfiguration();
483
    $configuration['link_text'] = t('Background media');
484
    $display->setConfiguration($configuration);
485
  }
486
  return $element;
487
}
488
489
/**
490
 * Callback to re-sort blocks into categories.
491
 *
492
 * @param array &$block_info
493
 *   An array of block plugin definitions.
494
 */
495
function df_tools_blocks_alter_block_categories(array &$block_info) {
496
  // Create an associative array which maps default => custom block categories.
497
  $category_map = [
498
    'Embed' => t('Existing Content'),
499
    'Entity Block' => t('Existing Content'),
500
    'Commerce' => t('Forms'),
501
    'Lists (Views)' => t('Lists'),
502
    'Listes (Views)' => t('Lists'),
503
    'Listas (Views)' => t('Lists'),
504
    'Views' => t('Lists'),
505
    'AddToAny' => t('Social'),
506
    'Product hero' => t('Hero'),
507
    'Workbench moderation' => t('Hidden'),
508
    'User' => t('Hidden'),
509
    'Utilisateur' => t('Hidden'),
510
    'Usuario' => t('Hidden'),
511
    'Chaos tools' => t('Hidden'),
512
    'Help' => t('Hidden'),
513
    'core' => t('Hidden'),
514
    'System' => t('Hidden'),
515
    'Moderation Dashboard' => t('Hidden'),
516
    'Entity Browser' => t('Hidden'),
517
    'Facets' => t('Hidden'),
518
    'Facets summary (Experimental)' => t('Hidden'),
519
    'Responsive Preview' => t('Hidden'),
520
    'DF Tools Blocks' => t('Hidden'),
521
  ];
522
523
  $label_map = [
524
    'Content Embed' => t('Content'),
525
    'Media Embed' => t('Media'),
526
  ];
527
528
  foreach ($block_info as $key => $info) {
529
    // Retrieve the name of the block category.
530
    $category = $info['category'];
531
    $label = $info['label'];
532
533
    // Retrieve the untranslated name of the category if it has been translated.
534
    if ($category instanceof TranslatableMarkup) {
535
      $category = $category->getUntranslatedString();
536
    }
537
    if ($label instanceof TranslatableMarkup) {
538
      $label = $label->getUntranslatedString();
539
    }
540
541
    // Move all fields of the currently panelized entity into a
542
    // 'Current @Entity_Type' category. If the block is not a field on the
543
    // current entity, allow its category to be remapped.
544
    if ($category === '@entity') {
545
      $block_info[$key]['category'] = $info['category']->render() . ' Fields';
546
    }
547
    // Place Block Content entities into categories based on their type.
548
    elseif ($category === 'Custom') {
549
      list($type, $uuid) = explode(':', $block_info[$key]['plugin_id']);
550
      unset($type);
551
      $ids = \Drupal::entityQuery('block_content')
552
        ->condition('uuid', $uuid, '=')
553
        ->execute();
554
      if ($block = BlockContent::load(reset($ids))) {
0 ignored issues
show
Bug introduced by
It seems like $ids can also be of type integer; however, parameter $array of reset() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

554
      if ($block = BlockContent::load(reset(/** @scrutinizer ignore-type */ $ids))) {
Loading history...
555
        if ($bundle = BlockContentType::load($block->bundle())) {
556
          $block_info[$key]['category'] = $bundle->label();
557
        }
558
      }
559
    }
560
561
    if (isset($block_info[$key])) {
562
      if (isset($category_map[$category])) {
563
        // Already translated.
564
        $block_info[$key]['category'] = $category_map[$category];
565
      }
566
      elseif (is_string($block_info[$key]['category'])) {
567
        // Already translated.
568
        $block_info[$key]['category'] = $block_info[$key]['category'];
569
      }
570
      if (isset($label_map[$label])) {
571
        // Already translated.
572
        $block_info[$key]['label'] = $label_map[$label];
573
      }
574
      elseif (is_string($block_info[$key]['label'])) {
575
        // Already translated.
576
        $block_info[$key]['label'] = $block_info[$key]['label'];
577
      }
578
    }
579
580
    if ($label === 'Entity gallery' && $category === 'Entity Block') {
581
      $block_info[$key]['category'] = t('Hidden');
582
    }
583
584
    if ($label === 'Entity Gallery Browser') {
585
      $block_info[$key]['category'] = t('Existing Content');
586
      $block_info[$key]['label'] = t('Gallery');
587
    }
588
  }
589
}
590
591
/**
592
 * Implements hook_panels_ipe_blocks_alter().
593
 *
594
 * Improves Panelizer/Panels IPE UX by removing fields that cannot be placed.
595
 */
596
function df_tools_blocks_panels_ipe_blocks_alter(&$block_info) {
597
  // Re-sort blocks into specific categories.
598
  df_tools_blocks_alter_block_categories($block_info);
599
  // Filter out fields that aren't relevant for this entity.
600
  $request = \Drupal::request();
601
  $storage_id = str_replace('*', '', $request->attributes->get('panels_storage_id', ''));
602
  list($entity_type, $id) = explode(':', $storage_id);
603
  $entity_type_manager = \Drupal::entityTypeManager();
604
  if (!empty($entity_type) && !empty($id) && $entity_type_manager->hasDefinition($entity_type)) {
605
    if ($entity = $entity_type_manager->getStorage($entity_type)->load($id)) {
606
      foreach ($block_info as $key => $info) {
607
        if ($info['id'] === 'entity_field') {
608
          list($block_id, $block_entity_type, $field_name) = explode(':', $info['plugin_id']);
609
          unset($block_id);
610
          if ($block_entity_type !== $entity_type || ($entity instanceof FieldableEntityInterface && !$entity->hasField($field_name))) {
611
            unset($block_info[$key]);
612
          }
613
        }
614
      }
615
    }
616
  }
617
  $block_info = array_values($block_info);
618
}
619
620
/**
621
 * Form submission handler for df_tools_blocks_form_alter().
622
 */
623
function df_tools_blocks_block_content_replicate($form, FormStateInterface $form_state) {
624
  // Retrieve block content entity from form_state.
625
  $entity = $form_state->getFormObject()->getEntity();
0 ignored issues
show
Bug introduced by
The method getEntity() does not exist on Drupal\Core\Form\FormInterface. It seems like you code against a sub-type of Drupal\Core\Form\FormInterface such as Drupal\Tests\media_acquiadam\unit\FormStub or Drupal\Core\Entity\EntityFormInterface or Drupal\Core\Entity\EntityForm or Drupal\image_widget_crop...eWidgetCropExamplesForm or Drupal\workspaces\Form\WorkspaceDeleteForm or Drupal\workspaces\Form\WorkspaceDeployForm or Drupal\workspaces\Form\WorkspaceForm or Drupal\workspaces\Form\WorkspaceActivateForm or Drupal\Core\Entity\ContentEntityConfirmFormBase or Drupal\Core\Entity\EntityConfirmFormBase or Drupal\webform\Form\Webf...figEntityDeleteFormBase or Drupal\webform\Form\WebformSubmissionDeleteForm. ( Ignorable by Annotation )

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

625
  $entity = $form_state->getFormObject()->/** @scrutinizer ignore-call */ getEntity();
Loading history...
626
  // Extract a few values from the entity.
627
  $block_info = $entity->get('info')->value;
628
  $block_id = $entity->id();
629
  // Replicate the block content entity.
630
  if (\Drupal::service('df_tools_blocks.copier')->makeCopy($entity)) {
631
    $message = t('Block Content: copied @info [id:@id]', ['@info' => $block_info, '@id' => $block_id]);
632
    \Drupal::logger('df_tools_blocks')->info($message);
633
    drupal_set_message($message, 'status');
0 ignored issues
show
Deprecated Code introduced by
The function drupal_set_message() has been deprecated: in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead. ( Ignorable by Annotation )

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

633
    /** @scrutinizer ignore-deprecated */ drupal_set_message($message, 'status');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
634
  }
635
  // Redirect to block list comes free!
636
}
637
638
/**
639
 * Implements hook_theme().
640
 */
641
function df_tools_blocks_theme($existing, $type, $theme, $path) {
642
  return [
643
    'code_block' => [
644
      'variables' => ['code' => NULL],
645
    ],
646
  ];
647
}
648