Paragraph.php 22.9 KB
Newer Older
Lennard Westerveld's avatar
Lennard Westerveld committed
1
2
3
4
<?php

namespace Drupal\paragraphs\Entity;

5
use Drupal\Component\Utility\NestedArray;
6
use Drupal\Component\Utility\Unicode;
7
use Drupal\Core\Entity\ContentEntityInterface;
8
use Drupal\Core\Entity\EntityPublishedTrait;
Lennard Westerveld's avatar
Lennard Westerveld committed
9
10
11
12
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;
13
use Drupal\Core\Field\ChangedFieldItemList;
14
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
15
use Drupal\Core\Field\FieldDefinitionInterface;
16
use Drupal\Core\Render\Markup;
17
use Drupal\Core\StringTranslation\StringTranslationTrait;
18
use Drupal\Core\TypedData\TranslatableInterface;
19
use Drupal\field\Entity\FieldStorageConfig;
20
use Drupal\entity_reference_revisions\EntityNeedsSaveTrait;
21
use Drupal\field\FieldConfigInterface;
Jeroen's avatar
Jeroen committed
22
use Drupal\paragraphs\ParagraphInterface;
23
use Drupal\user\EntityOwnerInterface;
Lennard Westerveld's avatar
Lennard Westerveld committed
24
25
26
use Drupal\user\UserInterface;

/**
Jeroen's avatar
Jeroen committed
27
 * Defines the Paragraph entity.
Lennard Westerveld's avatar
Lennard Westerveld committed
28
29
30
31
 *
 * @ingroup paragraphs
 *
 * @ContentEntityType(
Jeroen's avatar
Jeroen committed
32
33
 *   id = "paragraph",
 *   label = @Translation("Paragraph"),
34
35
36
37
38
39
40
 *   label_collection = @Translation("Paragraphs"),
 *   label_singular = @Translation("Paragraph"),
 *   label_plural = @Translation("Paragraphs"),
 *   label_count = @PluralTranslation(
 *     singular = "@count Paragraph",
 *     plural = "@count Paragraphs",
 *   ),
Jeroen's avatar
Jeroen committed
41
 *   bundle_label = @Translation("Paragraph type"),
Lennard Westerveld's avatar
Lennard Westerveld committed
42
 *   handlers = {
43
 *     "view_builder" = "Drupal\paragraphs\ParagraphViewBuilder",
44
 *     "access" = "Drupal\paragraphs\ParagraphAccessControlHandler",
45
 *     "storage_schema" = "Drupal\paragraphs\ParagraphStorageSchema",
46
47
48
49
 *     "form" = {
 *       "default" = "Drupal\Core\Entity\ContentEntityForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *       "edit" = "Drupal\Core\Entity\ContentEntityForm"
50
51
 *     },
 *     "views_data" = "Drupal\views\EntityViewsData",
Lennard Westerveld's avatar
Lennard Westerveld committed
52
53
 *   },
 *   base_table = "paragraphs_item",
54
55
56
 *   data_table = "paragraphs_item_field_data",
 *   revision_table = "paragraphs_item_revision",
 *   revision_data_table = "paragraphs_item_revision_field_data",
57
 *   translatable = TRUE,
58
59
60
 *   entity_revision_parent_type_field = "parent_type",
 *   entity_revision_parent_id_field = "parent_id",
 *   entity_revision_parent_field_name_field = "parent_field_name",
Lennard Westerveld's avatar
Lennard Westerveld committed
61
62
63
64
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "bundle" = "type",
Jeroen's avatar
Jeroen committed
65
 *     "langcode" = "langcode",
66
67
 *     "revision" = "revision_id",
 *     "published" = "status"
Lennard Westerveld's avatar
Lennard Westerveld committed
68
69
 *   },
 *   bundle_entity_type = "paragraphs_type",
70
 *   field_ui_base_route = "entity.paragraphs_type.edit_form",
71
 *   common_reference_revisions_target = TRUE,
72
 *   content_translation_ui_skip = TRUE,
73
 *   render_cache = FALSE,
74
75
76
77
78
79
80
 *   default_reference_revision_settings = {
 *     "field_storage_config" = {
 *       "cardinality" = -1,
 *       "settings" = {
 *         "target_type" = "paragraph"
 *       }
 *     },
Jeroen's avatar
Jeroen committed
81
82
83
84
85
 *     "field_config" = {
 *       "settings" = {
 *         "handler" = "default:paragraph"
 *       }
 *     },
86
 *     "entity_form_display" = {
87
 *       "type" = "paragraphs"
88
89
90
91
 *     },
 *     "entity_view_display" = {
 *       "type" = "entity_reference_revisions_entity_view"
 *     }
92
93
94
95
96
 *   },
 *   serialized_field_property_names = {
 *     "behavior_settings" = {
 *       "value"
 *     }
97
 *   }
Lennard Westerveld's avatar
Lennard Westerveld committed
98
99
 * )
 */
100
class Paragraph extends ContentEntityBase implements ParagraphInterface {
Lennard Westerveld's avatar
Lennard Westerveld committed
101

102
  use EntityNeedsSaveTrait;
103
  use EntityPublishedTrait;
104
  use StringTranslationTrait;
105

106
107
  /**
   * The behavior plugin data for the paragraph entity.
108
109
   *
   * @var array
110
111
112
   */
  protected $unserializedBehaviorSettings;

113
114
115
116
117
118
119
  /**
   * Number of summaries.
   *
   * @var int
   */
  protected $summaryCount;

120
121
122
123
124
125
126
  /**
   * {@inheritdoc}
   */
  public function getParentEntity() {
    if (!isset($this->get('parent_type')->value) || !isset($this->get('parent_id')->value)) {
      return NULL;
    }
127
128
129
130
131
132
133
134
135

    $parent = \Drupal::entityTypeManager()->getStorage($this->get('parent_type')->value)->load($this->get('parent_id')->value);

    // Return current translation of parent entity, if it exists.
    if ($parent != NULL && ($parent instanceof TranslatableInterface) && $parent->hasTranslation($this->language()->getId())) {
      return $parent->getTranslation($this->language()->getId());
    }

    return $parent;
136
137
  }

138
139
140
141
142
143
144
145
146
147
  /**
   * {@inheritdoc}
   */
  public function setParentEntity(ContentEntityInterface $parent, $parent_field_name) {
    $this->set('parent_type', $parent->getEntityTypeId());
    $this->set('parent_id', $parent->id());
    $this->set('parent_field_name', $parent_field_name);
    return $this;
  }

148
149
150
151
  /**
   * {@inheritdoc}
   */
  public function label() {
152
    if (($parent = $this->getParentEntity()) && $parent->hasField($this->get('parent_field_name')->value)) {
153
      $parent_field = $this->get('parent_field_name')->value;
154
      $field = $parent->get($parent_field);
155
156
157
      $label = $parent->label() . ' > ' . $field->getFieldDefinition()->getLabel();
      // A previous or draft revision or a deleted stale Paragraph.
      $postfix = ' (previous revision)';
158
      foreach ($field as $value) {
159
160
        if ($value->entity && $value->entity->getRevisionId() == $this->getRevisionId()) {
          $postfix = '';
161
          break;
162
163
        }
      }
164
165
      if ($postfix) {
        $label .= $postfix;
166
167
168
      }
    }
    else {
169
      $label = $this->t('Orphaned @type: @summary', ['@summary' => Unicode::truncate(strip_tags($this->getSummary()), 50, FALSE, TRUE), '@type' => $this->get('type')->entity->label()]);
170
171
172
173
    }
    return $label;
  }

Lennard Westerveld's avatar
Lennard Westerveld committed
174
175
176
  /**
   * {@inheritdoc}
   */
177
178
179
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);

180
181
182
183
184
185
186
    // If behavior settings are not set then get them from the entity.
    if ($this->unserializedBehaviorSettings !== NULL) {
      $this->set('behavior_settings', serialize($this->unserializedBehaviorSettings));
    }
  }

  /**
187
   * {@inheritdoc}
188
189
190
191
192
193
194
195
196
197
198
199
   */
  public function getAllBehaviorSettings() {
    if ($this->unserializedBehaviorSettings === NULL) {
      $this->unserializedBehaviorSettings = unserialize($this->get('behavior_settings')->value);
    }
    if (!is_array($this->unserializedBehaviorSettings)) {
      $this->unserializedBehaviorSettings = [];
    }
    return $this->unserializedBehaviorSettings;
  }

  /**
200
   * {@inheritdoc}
201
202
203
204
205
206
207
208
209
210
211
212
   */
  public function &getBehaviorSetting($plugin_id, $key, $default = NULL) {
    $settings = $this->getAllBehaviorSettings();
    $exists = NULL;
    $value = &NestedArray::getValue($settings, array_merge((array) $plugin_id, (array) $key), $exists);
    if (!$exists) {
      $value = $default;
    }
    return $value;
  }

  /**
213
   * {@inheritdoc}
214
215
216
217
218
219
220
   */
  public function setAllBehaviorSettings(array $settings) {
    // Set behavior settings fields.
    $this->unserializedBehaviorSettings = $settings;
  }

  /**
221
   * {@inheritdoc}
222
223
   */
  public function setBehaviorSettings($plugin_id, array $settings) {
224
225
    // Get existing behaviors first.
    $this->getAllBehaviorSettings();
226
227
    // Set behavior settings fields.
    $this->unserializedBehaviorSettings[$plugin_id] = $settings;
Lennard Westerveld's avatar
Lennard Westerveld committed
228
229
  }

230
231
232
233
234
235
236
237
  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    $this->setNeedsSave(FALSE);
    parent::postSave($storage, $update);
  }

238
239
240
241
242
243
244
  /**
   * {@inheritdoc}
   */
  public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
    parent::preSaveRevision($storage, $record);
  }

Lennard Westerveld's avatar
Lennard Westerveld committed
245
246
247
248
249
250
251
252
253
  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
254
255
256
   *
   * @deprecated Paragraphs no longer have their own author,
   *  check the parent entity instead.
Lennard Westerveld's avatar
Lennard Westerveld committed
257
258
   */
  public function getOwner() {
259
    $parent = $this->getParentEntity();
260
261
262
263
264
    if ($parent instanceof EntityOwnerInterface) {
      return $parent->getOwner();
    }
    else {
      return NULL;
265
    }
Lennard Westerveld's avatar
Lennard Westerveld committed
266
267
268
269
  }

  /**
   * {@inheritdoc}
270
271
272
   *
   * @deprecated Paragraphs no longer have their own author,
   *  check the parent entity instead.
Lennard Westerveld's avatar
Lennard Westerveld committed
273
274
   */
  public function getOwnerId() {
275
    $parent = $this->getParentEntity();
276
277
278
279
280
    if ($parent instanceof EntityOwnerInterface) {
      return $parent->getOwnerId();
    }
    else {
      return NULL;
281
    }
Lennard Westerveld's avatar
Lennard Westerveld committed
282
283
284
285
  }

  /**
   * {@inheritdoc}
286
287
288
   *
   * @deprecated Paragraphs no longer have their own author,
   *  check the parent entity instead.
Lennard Westerveld's avatar
Lennard Westerveld committed
289
290
291
292
293
294
295
   */
  public function setOwnerId($uid) {
    return $this;
  }

  /**
   * {@inheritdoc}
296
297
298
   *
   * @deprecated Paragraphs no longer have their own author,
   *  check the parent entity instead.
Lennard Westerveld's avatar
Lennard Westerveld committed
299
300
301
302
303
304
305
306
307
   */
  public function setOwner(UserInterface $account) {
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getType() {
Lennard Westerveld's avatar
Lennard Westerveld committed
308
    return $this->bundle();
Lennard Westerveld's avatar
Lennard Westerveld committed
309
  }
Lennard Westerveld's avatar
Lennard Westerveld committed
310

Lennard Westerveld's avatar
Lennard Westerveld committed
311
312
313
  /**
   * {@inheritdoc}
   */
314
315
  public function getParagraphType() {
    return $this->type->entity;
Lennard Westerveld's avatar
Lennard Westerveld committed
316
317
  }

Lennard Westerveld's avatar
Lennard Westerveld committed
318
319
  /**
   * {@inheritdoc}
320
321
322
   *
   * @deprecated Paragraphs no longer have their own author,
   *  check the parent entity instead.
Lennard Westerveld's avatar
Lennard Westerveld committed
323
324
   */
  public function getRevisionAuthor() {
325
326
327
328
329
330
331
    $parent = $this->getParentEntity();

    if ($parent) {
      return $parent->get('revision_uid')->entity;
    }

    return NULL;
Lennard Westerveld's avatar
Lennard Westerveld committed
332
333
334
335
  }

  /**
   * {@inheritdoc}
336
337
338
   *
   * @deprecated Paragraphs no longer have their own author,
   *  check the parent entity instead.
Lennard Westerveld's avatar
Lennard Westerveld committed
339
340
341
342
343
   */
  public function setRevisionAuthorId($uid) {
    return $this;
  }

Lennard Westerveld's avatar
Lennard Westerveld committed
344
345
346
347
  /**
   * {@inheritdoc}
   */
  public function getRevisionLog() {
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
348
    return '';
Lennard Westerveld's avatar
Lennard Westerveld committed
349
350
351
352
353
354
355
356
357
358
359
360
361
  }

  /**
   * {@inheritdoc}
   */
  public function setRevisionLog($revision_log) {
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
362
    $fields = parent::baseFieldDefinitions($entity_type);
Lennard Westerveld's avatar
Lennard Westerveld committed
363
364
365

    $fields['langcode'] = BaseFieldDefinition::create('language')
      ->setLabel(t('Language code'))
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
366
      ->setDescription(t('The paragraphs entity language code.'))
Lennard Westerveld's avatar
Lennard Westerveld committed
367
      ->setRevisionable(TRUE);
Lennard Westerveld's avatar
Lennard Westerveld committed
368

369
370
371
372
373
374
375
    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Published'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDefaultValue(TRUE)
      ->setDisplayConfigurable('form', TRUE);

Lennard Westerveld's avatar
Lennard Westerveld committed
376
    $fields['created'] = BaseFieldDefinition::create('created')
Lennard Westerveld's avatar
Lennard Westerveld committed
377
      ->setLabel(t('Authored on'))
Jeroen's avatar
Jeroen committed
378
      ->setDescription(t('The time that the Paragraph was created.'))
Lennard Westerveld's avatar
Lennard Westerveld committed
379
380
381
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', array(
382
        'region' => 'hidden',
383
        'weight' => 0,
Lennard Westerveld's avatar
Lennard Westerveld committed
384
385
      ))
      ->setDisplayConfigurable('form', TRUE);
Lennard Westerveld's avatar
Lennard Westerveld committed
386

387
388
389
    $fields['parent_id'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Parent ID'))
      ->setDescription(t('The ID of the parent entity of which this entity is referenced.'))
390
391
      ->setSetting('is_ascii', TRUE)
      ->setRevisionable(TRUE);
392
393
394
395
396

    $fields['parent_type'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Parent type'))
      ->setDescription(t('The entity parent type to which this entity is referenced.'))
      ->setSetting('is_ascii', TRUE)
397
398
      ->setSetting('max_length', EntityTypeInterface::ID_MAX_LENGTH)
      ->setRevisionable(TRUE);
399
400
401
402
403

    $fields['parent_field_name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Parent field name'))
      ->setDescription(t('The entity parent field name to which this entity is referenced.'))
      ->setSetting('is_ascii', TRUE)
404
405
      ->setSetting('max_length', FieldStorageConfig::NAME_MAX_LENGTH)
      ->setRevisionable(TRUE);
406

407
408
    $fields['behavior_settings'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Behavior settings'))
409
410
411
      ->setDescription(t('The behavior plugin settings'))
      ->setRevisionable(TRUE)
      ->setDefaultValue(serialize([]));
412

Lennard Westerveld's avatar
Lennard Westerveld committed
413
414
    return $fields;
  }
415

416
417
418
419
420
421
  /**
  * {@inheritdoc}
  */
 public function createDuplicate() {
   $duplicate = parent::createDuplicate();
   // Loop over entity fields and duplicate nested paragraphs.
422
423
424
425
426
   foreach ($duplicate->getFields() as $fieldItemList) {
     if ($fieldItemList instanceof EntityReferenceFieldItemListInterface && $fieldItemList->getSetting('target_type') === $this->getEntityTypeId()) {
       foreach ($fieldItemList as $delta => $item) {
         if ($item->entity) {
           $fieldItemList[$delta] = $item->entity->createDuplicate();
427
428
429
430
431
432
433
         }
       }
     }
   }
   return $duplicate;
 }

434
435
436
  /**
   * {@inheritdoc}
   */
437
  public function getSummary(array $options = []) {
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
    $summary_items = $this->getSummaryItems($options);
    $summary = [
      '#theme' => 'paragraphs_summary',
      '#summary' => $summary_items,
      '#expanded' => isset($options['expanded']) ? $options['expanded'] : FALSE,
    ];

    return \Drupal::service('renderer')->renderPlain($summary);
  }

  /**
   * {@inheritdoc}
   */
  public function getSummaryItems(array $options = []) {
    $summary = ['content' => [], 'behaviors' => []];
453
454
    $show_behavior_summary = isset($options['show_behavior_summary']) ? $options['show_behavior_summary'] : TRUE;
    $depth_limit = isset($options['depth_limit']) ? $options['depth_limit'] : 1;
455
456

    // Add content summary items.
457
    $this->summaryCount = 0;
458
    $components = \Drupal::service('entity_display.repository')->getFormDisplay('paragraph', $this->getType())->getComponents();
459
460
461
462
463
464
465
    uasort($components, 'Drupal\Component\Utility\SortArray::sortByWeightElement');
    foreach (array_keys($components) as $field_name) {
      // Components can be extra fields, check if the field really exists.
      if (!$this->hasField($field_name)) {
        continue;
      }
      $field_definition = $this->getFieldDefinition($field_name);
466
467
      // We do not add content to the summary from base fields, skip them
      // keeps performance while building the paragraph summary.
468
      if (!($field_definition instanceof FieldConfigInterface) || !$this->get($field_name)->access('view')) {
469
470
471
        continue;
      }

472
473
474
      if ($field_definition->getType() == 'image' || $field_definition->getType() == 'file') {
        $file_summary = $this->getFileSummary($field_name);
        if ($file_summary != '') {
475
          $summary['content'][] = $file_summary;
476
477
478
479
480
        }
      }

      $text_summary = $this->getTextSummary($field_name, $field_definition);
      if ($text_summary != '') {
481
        $summary['content'][] = $text_summary;
482
483
484
      }

      if ($field_definition->getType() == 'entity_reference_revisions') {
485
486
        // Decrease the depth, since we are entering a nested paragraph.
        $nested_summary = $this->getNestedSummary($field_name, [
487
          'show_behavior_summary' => FALSE,
488
489
          'depth_limit' => $depth_limit - 1
        ]);
490
        $summary['content'] = array_merge($summary['content'], $nested_summary);
491
492
      }

493
494
495
496
497
498
499
500
501
      if ($field_definition->getType() === 'entity_reference') {
        $referenced_entities = $this->get($field_name)->referencedEntities();
        /** @var \Drupal\Core\Entity\EntityInterface[] $referenced_entities */
        foreach ($referenced_entities as $referenced_entity) {
          if ($referenced_entity->access('view label')) {
            // Switch to the entity translation in the current context.
            $entity = \Drupal::service('entity.repository')->getTranslationFromContext($referenced_entity, $this->activeLangcode);
            $summary['content'][] = $entity->label();
          }
502
503
504
        }
      }

505
506
507
      // Add the Block admin label referenced by block_field.
      if ($field_definition->getType() == 'block_field') {
        if (!empty($this->get($field_name)->first())) {
508
509
510
          if ($block = $block_admin_label = $this->get($field_name)->first()->getBlock()) {
            $block_admin_label = $block->getPluginDefinition()['admin_label'];
          }
511
          $summary['content'][] = $block_admin_label;
512
513
        }
      }
514
515
516
517
518

      if ($field_definition->getType() == 'link') {
        if (!empty($this->get($field_name)->first())) {
          // If title is not set, fallback to the uri.
          if ($title = $this->get($field_name)->title) {
519
            $summary['content'][] = $title;
520
521
          }
          else {
522
            $summary['content'][] = $this->get($field_name)->uri;
523
524
525
          }
        }
      }
526
527
    }

528
    // Add behaviors summary items.
529
530
    if ($show_behavior_summary) {
      $paragraphs_type = $this->getParagraphType();
531
      foreach ($paragraphs_type->getEnabledBehaviorPlugins() as $plugin) {
532
        if ($plugin_summary = $plugin->settingsSummary($this)) {
533
534
535
536
537
538
          foreach ($plugin_summary as $plugin_summary_element) {
            if (!is_array($plugin_summary_element)) {
              $plugin_summary_element = ['value' => $plugin_summary_element];
            }
            $summary['behaviors'][] = $plugin_summary_element;
          }
539
        }
540
541
542
      }
    }

543
    return $summary;
544
545
546
547
548
549
550
551
552
553
554
555
556
  }

  /**
   * {@inheritdoc}
   */
  public function getIcons(array $options = []) {
    $show_behavior_info = isset($options['show_behavior_icon']) ? $options['show_behavior_icon'] : TRUE;
    $icons = [];

    // For now we depend here on the fact that summaryCount is already
    // initialized. That means that getSummary() should be called before
    // getIcons().
    // @todo - should we fix this dependency somehow?
557
    if ($this->summaryCount) {
558
559
560
561
562
      $icons['count'] = [
        '#markup' => $this->summaryCount,
        '#prefix' => '<span class="paragraphs-badge" title="' . (string) \Drupal::translation()->formatPlural($this->summaryCount, '1 child', '@count children') . '">',
        '#suffix' => '</span>',
      ];
563
564
    }

565
566
    if ($show_behavior_info) {
      $paragraphs_type = $this->getParagraphType();
567
      foreach ($paragraphs_type->getEnabledBehaviorPlugins() as $plugin) {
568
569
570
571
572
573
574
        if ($plugin_info = $plugin->settingsIcon($this)) {
          $icons = array_merge($icons, $plugin_info);
        }
      }
    }

    return $icons;
575
576
  }

577
578
579
580
581
582
583
584
585
  /**
   * Returns an array of field names to skip in ::isChanged.
   *
   * @return array
   *   An array of field names.
   */
  protected function getFieldsToSkipFromChangedCheck() {
    // A list of revision fields which should be skipped from the comparision.
    $fields = [
586
      $this->getEntityType()->getKey('revision')
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function isChanged() {
    if ($this->isNew()) {
      return TRUE;
    }

    // $this->original only exists during save. If it exists we re-use it here
    // for performance reasons.
    /** @var \Drupal\paragraphs\ParagraphInterface $original */
    $original = $this->original ?: NULL;
    if (!$original) {
      $original = $this->entityTypeManager()->getStorage($this->getEntityTypeId())->loadRevision($this->getLoadedRevisionId());
    }

    // If the current revision has just been added, we have a change.
    if ($original->isNewRevision()) {
      return TRUE;
    }

    // The list of fields to skip from the comparision.
    $skip_fields = $this->getFieldsToSkipFromChangedCheck();

    // Compare field item current values with the original ones to determine
    // whether we have changes. We skip also computed fields as comparing them
    // with their original values might not be possible or be meaningless.
    foreach ($this->getFieldDefinitions() as $field_name => $definition) {
      if (in_array($field_name, $skip_fields, TRUE)) {
        continue;
      }
      $field = $this->get($field_name);
      // When saving entities in the user interface, the changed timestamp is
      // automatically incremented by ContentEntityForm::submitForm() even if
      // nothing was actually changed. Thus, the changed time needs to be
      // ignored when determining whether there are any actual changes in the
      // entity.
      if (!($field instanceof ChangedFieldItemList) && !$definition->isComputed()) {
        $items = $field->filterEmptyItems();
        $original_items = $original->get($field_name)->filterEmptyItems();
        if (!$items->equals($original_items)) {
          return TRUE;
        }
      }
    }

    return FALSE;
  }

641
642
643
644
645
646
647
648
649
650
651
652
  /**
   * Returns summary for file paragraph.
   *
   * @param string $field_name
   *   Field name from field definition.
   *
   * @return string
   *   Summary for image.
   */
  protected function getFileSummary($field_name) {
    $summary = '';
    if ($this->get($field_name)->entity) {
653
      foreach ($this->get($field_name) as $file_value) {
654
655
656
657
658
659
660
661
662
663
664

        $text = '';
        if ($file_value->description != '') {
          $text = $file_value->description;
        }
        elseif ($file_value->title != '') {
          $text = $file_value->title;
        }
        elseif ($file_value->alt != '') {
          $text = $file_value->alt;
        }
665
        elseif ($file_value->entity && $file_value->entity->getFileName()) {
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
          $text = $file_value->entity->getFileName();
        }

        if (strlen($text) > 150) {
          $text = Unicode::truncate($text, 150);
        }

        $summary = $text;
      }
    }

    return trim($summary);
  }

  /**
681
   * Returns summary items for nested paragraphs.
682
683
684
   *
   * @param string $field_name
   *   Field definition id for paragraph.
685
686
687
688
   * @param array $options
   *   (optional) An associative array of additional options.
   *   See \Drupal\paragraphs\ParagraphInterface::getSummary() for all of the
   *   available options.
689
   *
690
691
   * @return array
   *   List of content summary items for nested elements.
692
   */
693
  protected function getNestedSummary($field_name, array $options) {
694
    $summary_content = [];
695
696
697
698
    if ($options['depth_limit'] >= 0) {
      foreach ($this->get($field_name) as $item) {
        $entity = $item->entity;
        if ($entity instanceof ParagraphInterface) {
699
700
          // Switch to the entity translation in the current context if exists.
          $entity = \Drupal::service('entity.repository')->getTranslationFromContext($entity, $this->activeLangcode);
701
702
          $content_summary_items = $entity->getSummaryItems($options)['content'];
          $summary_content = array_merge($summary_content, array_values($content_summary_items));
703
704
          $this->summaryCount++;
        }
705
706
707
      }
    }

708
    return $summary_content;
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
  }

  /**
   * Returns summary for all text type paragraph.
   *
   * @param string $field_name
   *   Field definition id for paragraph.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   Field definition for paragraph.
   *
   * @return string
   *   Short summary for text paragraph.
   */
  public function getTextSummary($field_name, FieldDefinitionInterface $field_definition) {
    $text_types = [
      'text_with_summary',
      'text',
      'text_long',
      'list_string',
      'string',
    ];

    $excluded_text_types = [
      'parent_id',
      'parent_type',
      'parent_field_name',
    ];

    $summary = '';
    if (in_array($field_definition->getType(), $text_types)) {
      if (in_array($field_name, $excluded_text_types)) {
740
        return '';
741
742
      }

743
      $text = $this->get($field_name)->value ?? '';
744
      $summary = Unicode::truncate(trim(strip_tags($text)), 150);
745
      if (empty($summary)) {
746
747
748
        // Autoescape is applied to the summary when it is rendered with twig,
        // make it a Markup object so HTML tags are displayed correctly.
        $summary = Markup::create(Unicode::truncate(htmlspecialchars(trim($text)), 150));
749
      }
750
751
    }

752
    return $summary;
753
754
  }

Lennard Westerveld's avatar
Lennard Westerveld committed
755
}