You are here

public function EntityReferenceFieldSerializer::onSerializeContentField in Acquia Content Hub 8.2

Extract entity uuids as field values.

Parameters

\Drupal\acquia_contenthub\Event\SerializeCdfEntityFieldEvent $event: The content entity field serialization event.

Throws

\Exception

1 call to EntityReferenceFieldSerializer::onSerializeContentField()
EntityReferenceImageFieldSerializer::onSerializeContentField in src/EventSubscriber/SerializeContentField/EntityReferenceImageFieldSerializer.php
Extract entity uuids as field values.
1 method overrides EntityReferenceFieldSerializer::onSerializeContentField()
EntityReferenceImageFieldSerializer::onSerializeContentField in src/EventSubscriber/SerializeContentField/EntityReferenceImageFieldSerializer.php
Extract entity uuids as field values.

File

src/EventSubscriber/SerializeContentField/EntityReferenceFieldSerializer.php, line 42

Class

EntityReferenceFieldSerializer
Subscribes to entity field serialization to handle entity references.

Namespace

Drupal\acquia_contenthub\EventSubscriber\SerializeContentField

Code

public function onSerializeContentField(SerializeCdfEntityFieldEvent $event) {
  if (!in_array($event
    ->getField()
    ->getFieldDefinition()
    ->getType(), $this->fieldTypes)) {
    return;
  }
  $cdf = $event
    ->getCdf();
  $metadata = $cdf
    ->getMetadata();
  $metadata['field'][$event
    ->getFieldName()] = [
    'type' => $event
      ->getField()
      ->getFieldDefinition()
      ->getType(),
    'target' => $event
      ->getField()
      ->getFieldDefinition()
      ->getFieldStorageDefinition()
      ->getSetting('target_type'),
  ];
  $cdf
    ->setMetadata($metadata);
  $data = [];

  /** @var \Drupal\Core\Entity\TranslatableInterface $entity */
  $entity = $event
    ->getEntity();
  foreach ($entity
    ->getTranslationLanguages() as $langcode => $language) {
    $field = $event
      ->getFieldTranslation($langcode);
    if ($field
      ->isEmpty()) {
      $data['value'][$langcode] = [];
      continue;
    }
    if ($event
      ->getFieldName() != $event
      ->getEntity()
      ->getEntityType()
      ->getKey('bundle')) {
      foreach ($field as $item) {
        if (!$item->entity) {
          $entity = \Drupal::entityTypeManager()
            ->getStorage($event
            ->getField()
            ->getFieldDefinition()
            ->getSetting('target_type'))
            ->load($item
            ->getValue()['target_id']);
          if (is_null($entity)) {
            continue;
          }
          $item->entity = $entity;
        }
        $data['value'][$langcode][] = $item->entity
          ->uuid();
      }
    }
    else {
      foreach ($field as $item) {
        $data['value'][$langcode] = $item->entity
          ->uuid();
      }
    }
  }
  $event
    ->setFieldData($data);
  $event
    ->stopPropagation();
}