You are here

final class ReferenceUpgrader in Inline Entity Form 8

Class ReferenceUpgrader

When saving nested IEFs inside-out, after saving an inner entity, we must "upgrade" its reference item with e.g. revision ID information.

Hierarchy

Expanded class hierarchy of ReferenceUpgrader

See also

\Drupal\inline_entity_form\WidgetSubmit

File

src/ReferenceUpgrader.php, line 19

Namespace

Drupal\inline_entity_form
View source
final class ReferenceUpgrader {

  /**
   * Registered entities, keyed by entity type, then ID.
   *
   * @var array
   */
  private $entities = [];
  public function registerEntity(EntityInterface $entity) {
    $entityId = $entity
      ->id() ?? $this
      ->throwNeedsId();
    $this->entities[$entity
      ->getEntityTypeId()][$entityId] = $entity;
  }
  private function throwNeedsId() {
    throw new \RuntimeException("Can only register entity with ID.");
  }
  public function upgradeEntityReferences(FieldableEntityInterface $entity) {
    foreach ($entity as $fieldName => $fieldItemList) {
      if ($fieldItemList instanceof EntityReferenceFieldItemListInterface && ($targetEntityType = $fieldItemList
        ->getFieldDefinition()
        ->getSetting('target_type')) && ($itemDefinition = $fieldItemList
        ->getItemDefinition()) && $itemDefinition instanceof FieldItemDataDefinitionInterface && $itemDefinition
        ->getPropertyDefinition('target_id')) {
        foreach ($fieldItemList as $fieldItem) {
          assert($fieldItem instanceof FieldItemInterface);
          if ($targetId = $fieldItem->target_id) {
            if ($targetEntity = $this->entities[$targetEntityType][$targetId] ?? NULL) {
              $fieldItem
                ->setValue($targetEntity);
            }
          }
        }
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ReferenceUpgrader::$entities private property Registered entities, keyed by entity type, then ID.
ReferenceUpgrader::registerEntity public function
ReferenceUpgrader::throwNeedsId private function
ReferenceUpgrader::upgradeEntityReferences public function