You are here

public function ParentEntityDeleteUpdater::moveChildren in Entity Reference Hierarchy 8.2

Same name and namespace in other branches
  1. 3.x src/Storage/ParentEntityDeleteUpdater.php \Drupal\entity_hierarchy\Storage\ParentEntityDeleteUpdater::moveChildren()

Moves children to their grandparent or root.

Parameters

\Drupal\Core\Entity\ContentEntityInterface $parent: Parent being deleted.

File

src/Storage/ParentEntityDeleteUpdater.php, line 56

Class

ParentEntityDeleteUpdater
Defines a class for updating the tree when a parent is deleted.

Namespace

Drupal\entity_hierarchy\Storage

Code

public function moveChildren(ContentEntityInterface $parent) {
  if (!$parent
    ->isDefaultRevision()) {

    // We don't do anything here.
    return;
  }
  if (!($fields = $this->parentCandidate
    ->getCandidateFields($parent))) {

    // There are no fields that could point to this entity.
    return;
  }
  $stubNode = $this->nodeKeyFactory
    ->fromEntity($parent);
  foreach ($fields as $field_name) {

    /** @var \Pnx\NestedSet\NestedSetInterface $storage */
    $storage = $this->nestedSetStorageFactory
      ->get($field_name, $parent
      ->getEntityTypeId());
    if ($children = $storage
      ->findChildren($stubNode)) {
      $parentNode = $storage
        ->findParent($stubNode);
      $childEntities = $this->treeNodeMapper
        ->loadEntitiesForTreeNodesWithoutAccessChecks($parent
        ->getEntityTypeId(), $children);
      foreach ($childEntities as $child_node) {
        if (!$childEntities
          ->offsetExists($child_node)) {
          continue;
        }
        $child_entity = $childEntities
          ->offsetGet($child_node);
        $child_entity->{$field_name}->target_id = $parentNode ? $parentNode
          ->getId() : NULL;
        if ($child_entity
          ->getEntityType()
          ->hasKey('revision')) {

          // We don't want a new revision here.
          $child_entity
            ->setNewRevision(FALSE);
        }
        $child_entity
          ->save();
      }
    }
    $this
      ->lockTree($field_name, $parent
      ->getEntityTypeId());
    if ($existingNode = $storage
      ->getNode($stubNode)) {
      $storage
        ->deleteNode($existingNode);
    }
    $this
      ->releaseLock($field_name, $parent
      ->getEntityTypeId());
  }
}