Paragraph.php 22.8 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 224 225
   */
  public function setBehaviorSettings($plugin_id, array $settings) {
    // Set behavior settings fields.
    $this->unserializedBehaviorSettings[$plugin_id] = $settings;
Lennard Westerveld's avatar
Lennard Westerveld committed
226 227
  }

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

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

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

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

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

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

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

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

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

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

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

    return NULL;
Lennard Westerveld's avatar
Lennard Westerveld committed
330 331 332 333
  }

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

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

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

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

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

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

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

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

    $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)
395 396
      ->setSetting('max_length', EntityTypeInterface::ID_MAX_LENGTH)
      ->setRevisionable(TRUE);
397 398 399 400 401

    $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)
402 403
      ->setSetting('max_length', FieldStorageConfig::NAME_MAX_LENGTH)
      ->setRevisionable(TRUE);
404

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

Lennard Westerveld's avatar
Lennard Westerveld committed
411 412
    return $fields;
  }
413

414 415 416 417 418 419
  /**
  * {@inheritdoc}
  */
 public function createDuplicate() {
   $duplicate = parent::createDuplicate();
   // Loop over entity fields and duplicate nested paragraphs.
420 421 422 423 424
   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();
425 426 427 428 429 430 431
         }
       }
     }
   }
   return $duplicate;
 }

432 433 434
  /**
   * {@inheritdoc}
   */
435
  public function getSummary(array $options = []) {
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    $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' => []];
451 452
    $show_behavior_summary = isset($options['show_behavior_summary']) ? $options['show_behavior_summary'] : TRUE;
    $depth_limit = isset($options['depth_limit']) ? $options['depth_limit'] : 1;
453 454

    // Add content summary items.
455
    $this->summaryCount = 0;
456
    $components = \Drupal::service('entity_display.repository')->getFormDisplay('paragraph', $this->getType())->getComponents();
457 458 459 460 461 462 463
    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);
464 465
      // We do not add content to the summary from base fields, skip them
      // keeps performance while building the paragraph summary.
466
      if (!($field_definition instanceof FieldConfigInterface) || !$this->get($field_name)->access('view')) {
467 468 469
        continue;
      }

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

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

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

491 492 493 494 495 496 497 498 499
      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();
          }
500 501 502
        }
      }

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

      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) {
517
            $summary['content'][] = $title;
518 519
          }
          else {
520
            $summary['content'][] = $this->get($field_name)->uri;
521 522 523
          }
        }
      }
524 525
    }

526
    // Add behaviors summary items.
527 528
    if ($show_behavior_summary) {
      $paragraphs_type = $this->getParagraphType();
529
      foreach ($paragraphs_type->getEnabledBehaviorPlugins() as $plugin) {
530
        if ($plugin_summary = $plugin->settingsSummary($this)) {
531 532 533 534 535 536
          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;
          }
537
        }
538 539 540
      }
    }

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

  /**
   * {@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?
555
    if ($this->summaryCount) {
556 557 558 559 560
      $icons['count'] = [
        '#markup' => $this->summaryCount,
        '#prefix' => '<span class="paragraphs-badge" title="' . (string) \Drupal::translation()->formatPlural($this->summaryCount, '1 child', '@count children') . '">',
        '#suffix' => '</span>',
      ];
561 562
    }

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

    return $icons;
573 574
  }

575 576 577 578 579 580 581 582 583
  /**
   * 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 = [
584
      $this->getEntityType()->getKey('revision')
585 586 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
    ];

    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;
  }

639 640 641 642 643 644 645 646 647 648 649 650
  /**
   * 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) {
651
      foreach ($this->get($field_name) as $file_value) {
652 653 654 655 656 657 658 659 660 661 662

        $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;
        }
663
        elseif ($file_value->entity && $file_value->entity->getFileName()) {
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
          $text = $file_value->entity->getFileName();
        }

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

        $summary = $text;
      }
    }

    return trim($summary);
  }

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

706
    return $summary_content;
707 708 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
  }

  /**
   * 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)) {
738
        return '';
739 740 741
      }

      $text = $this->get($field_name)->value;
742
      $summary = Unicode::truncate(trim(strip_tags($text)), 150);
743
      if (empty($summary)) {
744 745 746
        // 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));
747
      }
748 749
    }

750
    return $summary;
751 752
  }

Lennard Westerveld's avatar
Lennard Westerveld committed
753
}