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 ( fcb063...c48194 )
by Kevin
05:17
created

_layout_builder_block_form_alter()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 44
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 34
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 44
rs 9.0648
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
    $element['field_hero_link']['widget'][0]['uri']['#prefix'] = '<div class="col-6">';
297
    $element['field_hero_link']['widget'][0]['uri']['#suffix'] = '</div>';
298
    $element['field_hero_link']['widget'][0]['title']['#prefix'] = '<div class="col-6">';
299
    $element['field_hero_link']['widget'][0]['title']['#suffix'] = '</div>';
300
    $style_fields = [
301
      'field_text_color',
302
      'field_first_line_size',
303
      'field_second_line_size',
304
      'field_gradient_color',
305
      'field_callout_color',
306
      'field_callout_width',
307
      'field_callout_background_color',
308
      'field_callout_background_opacity',
309
      'field_hero_alignment',
310
    ];
311
    $element['style_fields'] = [
312
      '#type' => 'details',
313
      '#title' => t('Advanced settings'),
314
      '#weight' => 2,
315
    ];
316
317
    foreach ($style_fields as $field) {
318
      if ((strpos($field, 'color') !== FALSE) && isset($element[$field])) {
319
          $element[$field]['widget'][0]['value']['#type'] = 'color';
320
      }
321
      $element[$field]['#attributes']['class'][] = 'col-4';
322
      $element['style_fields'][] = $element[$field];
323
      $element['style_fields']['#weight'] = $element[$field]['#weight'];
324
      unset($element[$field]);
325
    }
326
  }
327
  return $element;
328
}
329
330
/**
331
 * Implements hook_form_FORM_ID_alter().
332
 */
333
function df_tools_blocks_form_panels_ipe_block_plugin_form_alter(&$form, FormStateInterface $form_state, $form_id) {
334
  // Modify the block placement form.
335
  if (isset($form['flipper']['front']['settings']['admin_label'])) {
336
    $form['flipper']['front']['settings']['admin_label']['#weight'] = -2;
337
  }
338
339
  if (isset($form['flipper']['front']['settings']['label_display'])) {
340
    if (empty($form['uuid']['#value'])) {
341
      $form['flipper']['front']['settings']['label_display']['#default_value'] = FALSE;
342
    }
343
    $form['flipper']['front']['settings']['label_display']['#weight'] = -1;
344
  }
345
346
  if (isset($form['flipper']['front']['settings']['label'])) {
347
    $form['flipper']['front']['settings']['label']['#weight'] = 0;
348
    $form['flipper']['front']['settings']['label']['#states'] = [
349
      'visible' => [
350
        ':input[name="settings[label_display]"]' => ['checked' => TRUE],
351
      ],
352
    ];
353
  }
354
355
  // Add special logic for the Entity Browser block plugins.
356
  if (isset($form['plugin_id'])) {
357
    if ($form['plugin_id']['#value'] === 'content_embed') {
358
      // Only auto-open the Content Embed block if it is empty.
359
      if (empty(Element::getVisibleChildren($form['flipper']['front']['settings']['selection']['table'])) && !$form_state->isProcessingInput()) {
360
        $form['#attached']['library'][] = 'df_tools_blocks/auto_open';
361
        $form['#attributes']['data-df-tools-blocks-auto-open'] = 'settings_selection_nids_entity_browser';
362
      }
363
364
      // Modify the Content Embed form to guide users to valid View Modes.
365
      if (empty($form['flipper']['front']['settings']['view_mode']['#default_value'])) {
366
        $form['flipper']['front']['settings']['view_mode']['#default_value'] = 'featured';
367
      }
368
      $excluded_modes = [
369
        'basic_info',
370
        'content_browser',
371
        'rss',
372
        'search_index',
373
        'search_result',
374
        'token',
375
        'full',
376
        'df',
377
      ];
378
      foreach ($excluded_modes as $view_mode) {
379
        if (isset($form['flipper']['front']['settings']['view_mode']['#options'][$view_mode])) {
380
          unset($form['flipper']['front']['settings']['view_mode']['#options'][$view_mode]);
381
        }
382
      }
383
    }
384
    elseif ($form['plugin_id']['#value'] === 'media_embed') {
385
      if (empty(Element::getVisibleChildren($form['flipper']['front']['settings']['selection']['table'])) && !$form_state->isProcessingInput()) {
386
        $form['#attached']['library'][] = 'df_tools_blocks/auto_open';
387
        $form['#attributes']['data-df-tools-blocks-auto-open'] = 'settings_selection_mids_entity_browser';
388
      }
389
      $excluded_modes = [
390
        'media_browser',
391
        'product_slideshow_thumbnail',
392
        'hero_thin',
393
        'hero_product',
394
        'embedded',
395
        'token',
396
      ];
397
      foreach ($excluded_modes as $view_mode) {
398
        if (isset($form['flipper']['front']['settings']['view_mode']['#options'][$view_mode])) {
399
          unset($form['flipper']['front']['settings']['view_mode']['#options'][$view_mode]);
400
        }
401
      }
402
    }
403
  }
404
}
405
406
/**
407
 * Implements hook_form_FORM_ID_alter().
408
 */
409
function df_tools_blocks_form_block_content_hero_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
410
  df_tools_blocks_form_block_content_hero_panels_ipe_form_alter($form, $form_state, $form_id);
411
}
412
413
/**
414
 * Implements hook_form_FORM_ID_alter().
415
 */
416
function df_tools_blocks_form_block_content_hero_panels_ipe_form_alter(&$form, FormStateInterface $form_state, $form_id) {
417
  // Move the hero image out of the details element and set a better label.
418
  $form['field_hero_background']['widget']['#type'] = 'container';
419
  $form['field_hero_background']['widget']['entity_browser']['#process'][] = '_df_tools_blocks_hero_browser_button';
420
  // Remove the link fieldset and put the URI and title side-by-side.
421
  $form['field_hero_link']['widget'][0]['#type'] = 'container';
422
  $form['field_hero_link']['widget'][0]['#attributes']['class'][] = 'row';
423
  unset($form['field_hero_link']['widget'][0]['uri']['#description']);
424
  $form['field_hero_link']['widget'][0]['uri']['#title'] = t('Callout link');
425
  $form['field_hero_link']['widget'][0]['title']['#title'] = t('Callout text');
426
  $form['field_hero_link']['widget'][0]['uri']['#prefix'] = '<div class="large-6 columns">';
427
  $form['field_hero_link']['widget'][0]['uri']['#suffix'] = '</div>';
428
  $form['field_hero_link']['widget'][0]['title']['#prefix'] = '<div class="large-6 columns">';
429
  $form['field_hero_link']['widget'][0]['title']['#suffix'] = '</div>';
430
  // Group complex form elements into the advanced section.
431
  $form['field_icon']['#attributes']['class'][] = 'visually-hidden';
432
  $form['field_nested_block']['#attributes']['class'][] = 'visually-hidden';
433
  $style_fields = [
434
    'field_text_color',
435
    'field_gradient_color',
436
    'field_callout_color',
437
    'field_callout_background_color',
438
  ];
439
  $form['style_fields'] = [
440
    '#type' => 'container',
441
    '#attributes' => ['class' => ['row']],
442
  ];
443
  foreach ($style_fields as $field) {
444
    if (strpos($field, 'color') !== FALSE) {
445
      $form[$field]['widget'][0]['value']['#type'] = 'color';
446
    }
447
    $form[$field]['#attributes']['class'][] = 'large-4 columns';
448
    $form['style_fields'][] = $form[$field];
449
    $form['style_fields']['#weight'] = $form[$field]['#weight'];
450
    unset($form[$field]);
451
  }
452
}
453
454
/**
455
 * Does nit-picky changes on the Hero image entity browser.
456
 *
457
 * @param array $element
458
 *   The element render array.
459
 *
460
 * @return array
461
 *   The possibly modified form render array.
462
 */
463
function _df_tools_blocks_hero_browser_button(array $element) {
464
  $element['entity_browser']['open_modal']['#value'] = t('Select background');
465
  if (isset($element['entity_browser']['open_modal']['#ajax'])) {
466
    /** @var \Drupal\entity_browser\DisplayInterface $display */
467
    $display = $element['entity_browser']['open_modal']['#ajax']['callback'][0];
468
    $configuration = $display->getConfiguration();
469
    $configuration['link_text'] = t('Background media');
470
    $display->setConfiguration($configuration);
471
  }
472
  return $element;
473
}
474
475
/**
476
 * Callback to re-sort blocks into categories.
477
 *
478
 * @param array &$block_info
479
 *   An array of block plugin definitions.
480
 */
481
function df_tools_blocks_alter_block_categories(array &$block_info) {
482
  // Create an associative array which maps default => custom block categories.
483
  $category_map = [
484
    'Embed' => t('Existing Content'),
485
    'Entity Block' => t('Existing Content'),
486
    'Commerce' => t('Forms'),
487
    'Lists (Views)' => t('Lists'),
488
    'Listes (Views)' => t('Lists'),
489
    'Listas (Views)' => t('Lists'),
490
    'Views' => t('Lists'),
491
    'AddToAny' => t('Social'),
492
    'Product hero' => t('Hero'),
493
    'Workbench moderation' => t('Hidden'),
494
    'User' => t('Hidden'),
495
    'Utilisateur' => t('Hidden'),
496
    'Usuario' => t('Hidden'),
497
    'Chaos tools' => t('Hidden'),
498
    'Help' => t('Hidden'),
499
    'core' => t('Hidden'),
500
    'System' => t('Hidden'),
501
    'Moderation Dashboard' => t('Hidden'),
502
    'Entity Browser' => t('Hidden'),
503
    'Facets' => t('Hidden'),
504
    'Facets summary (Experimental)' => t('Hidden'),
505
    'Responsive Preview' => t('Hidden'),
506
    'DF Tools Blocks' => t('Hidden'),
507
  ];
508
509
  $label_map = [
510
    'Content Embed' => t('Content'),
511
    'Media Embed' => t('Media'),
512
  ];
513
514
  foreach ($block_info as $key => $info) {
515
    // Retrieve the name of the block category.
516
    $category = $info['category'];
517
    $label = $info['label'];
518
519
    // Retrieve the untranslated name of the category if it has been translated.
520
    if ($category instanceof TranslatableMarkup) {
521
      $category = $category->getUntranslatedString();
522
    }
523
    if ($label instanceof TranslatableMarkup) {
524
      $label = $label->getUntranslatedString();
525
    }
526
527
    // Move all fields of the currently panelized entity into a
528
    // 'Current @Entity_Type' category. If the block is not a field on the
529
    // current entity, allow its category to be remapped.
530
    if ($category === '@entity') {
531
      $block_info[$key]['category'] = $info['category']->render() . ' Fields';
532
    }
533
    // Place Block Content entities into categories based on their type.
534
    elseif ($category === 'Custom') {
535
      list($type, $uuid) = explode(':', $block_info[$key]['plugin_id']);
536
      unset($type);
537
      $ids = \Drupal::entityQuery('block_content')
538
        ->condition('uuid', $uuid, '=')
539
        ->execute();
540
      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

540
      if ($block = BlockContent::load(reset(/** @scrutinizer ignore-type */ $ids))) {
Loading history...
541
        if ($bundle = BlockContentType::load($block->bundle())) {
542
          $block_info[$key]['category'] = $bundle->label();
543
        }
544
      }
545
    }
546
547
    if (isset($block_info[$key])) {
548
      if (isset($category_map[$category])) {
549
        // Already translated.
550
        $block_info[$key]['category'] = $category_map[$category];
551
      }
552
      elseif (is_string($block_info[$key]['category'])) {
553
        // Already translated.
554
        $block_info[$key]['category'] = $block_info[$key]['category'];
555
      }
556
      if (isset($label_map[$label])) {
557
        // Already translated.
558
        $block_info[$key]['label'] = $label_map[$label];
559
      }
560
      elseif (is_string($block_info[$key]['label'])) {
561
        // Already translated.
562
        $block_info[$key]['label'] = $block_info[$key]['label'];
563
      }
564
    }
565
566
    if ($label === 'Entity gallery' && $category === 'Entity Block') {
567
      $block_info[$key]['category'] = t('Hidden');
568
    }
569
570
    if ($label === 'Entity Gallery Browser') {
571
      $block_info[$key]['category'] = t('Existing Content');
572
      $block_info[$key]['label'] = t('Gallery');
573
    }
574
  }
575
}
576
577
/**
578
 * Implements hook_panels_ipe_blocks_alter().
579
 *
580
 * Improves Panelizer/Panels IPE UX by removing fields that cannot be placed.
581
 */
582
function df_tools_blocks_panels_ipe_blocks_alter(&$block_info) {
583
  // Re-sort blocks into specific categories.
584
  df_tools_blocks_alter_block_categories($block_info);
585
  // Filter out fields that aren't relevant for this entity.
586
  $request = \Drupal::request();
587
  $storage_id = str_replace('*', '', $request->attributes->get('panels_storage_id', ''));
588
  list($entity_type, $id) = explode(':', $storage_id);
589
  $entity_type_manager = \Drupal::entityTypeManager();
590
  if (!empty($entity_type) && !empty($id) && $entity_type_manager->hasDefinition($entity_type)) {
591
    if ($entity = $entity_type_manager->getStorage($entity_type)->load($id)) {
592
      foreach ($block_info as $key => $info) {
593
        if ($info['id'] === 'entity_field') {
594
          list($block_id, $block_entity_type, $field_name) = explode(':', $info['plugin_id']);
595
          unset($block_id);
596
          if ($block_entity_type !== $entity_type || ($entity instanceof FieldableEntityInterface && !$entity->hasField($field_name))) {
597
            unset($block_info[$key]);
598
          }
599
        }
600
      }
601
    }
602
  }
603
  $block_info = array_values($block_info);
604
}
605
606
/**
607
 * Form submission handler for df_tools_blocks_form_alter().
608
 */
609
function df_tools_blocks_block_content_replicate($form, FormStateInterface $form_state) {
610
  // Retrieve block content entity from form_state.
611
  $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

611
  $entity = $form_state->getFormObject()->/** @scrutinizer ignore-call */ getEntity();
Loading history...
612
  // Extract a few values from the entity.
613
  $block_info = $entity->get('info')->value;
614
  $block_id = $entity->id();
615
  // Replicate the block content entity.
616
  if (\Drupal::service('df_tools_blocks.copier')->makeCopy($entity)) {
617
    $message = t('Block Content: copied @info [id:@id]', ['@info' => $block_info, '@id' => $block_id]);
618
    \Drupal::logger('df_tools_blocks')->info($message);
619
    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

619
    /** @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...
620
  }
621
  // Redirect to block list comes free!
622
}
623
624
/**
625
 * Implements hook_theme().
626
 */
627
function df_tools_blocks_theme($existing, $type, $theme, $path) {
628
  return [
629
    'code_block' => [
630
      'variables' => ['code' => NULL],
631
    ],
632
  ];
633
}
634