You are here

public function EntityReferenceHierarchy::getInsertPosition in Entity Reference Hierarchy 8.2

Same name and namespace in other branches
  1. 3.x src/Plugin/Field/FieldType/EntityReferenceHierarchy.php \Drupal\entity_hierarchy\Plugin\Field\FieldType\EntityReferenceHierarchy::getInsertPosition()

Gets the insert position for the new child.

Parameters

array $weightOrderedSiblings: Sibling nodes, grouped by weight.

int $weight: Desired weight amongst siblings of the new child.

bool $isNewNode: TRUE if the node is brand new, FALSE if it needs to be moved from elsewhere in the tree.

Return value

\Drupal\entity_hierarchy\Storage\InsertPosition|bool Insert position, FALSE if the siblings no longer exist.

1 call to EntityReferenceHierarchy::getInsertPosition()
EntityReferenceHierarchy::postSave in src/Plugin/Field/FieldType/EntityReferenceHierarchy.php
Defines custom post-save behavior for field values.

File

src/Plugin/Field/FieldType/EntityReferenceHierarchy.php, line 327

Class

EntityReferenceHierarchy
Plugin implementation of the 'entity_reference_hierarchy' field type.

Namespace

Drupal\entity_hierarchy\Plugin\Field\FieldType

Code

public function getInsertPosition(array $weightOrderedSiblings, $weight, $isNewNode) {
  if (isset($weightOrderedSiblings[$weight])) {

    // There are already nodes at the same weight, insert it with them.
    return new InsertPosition(end($weightOrderedSiblings[$weight]), $isNewNode, InsertPosition::DIRECTION_AFTER);
  }

  // There are no nodes at this weight, we need to find the right position.
  $firstGroup = reset($weightOrderedSiblings);
  $start = key($weightOrderedSiblings);
  if ($weight < $start) {

    // We're going to position before all existing nodes.
    return new InsertPosition(reset($firstGroup), $isNewNode);
  }
  foreach (array_keys($weightOrderedSiblings) as $weightPosition) {
    if ($weight < $weightPosition) {
      return new InsertPosition(reset($weightOrderedSiblings[$weightPosition]), $isNewNode);
    }
  }

  // We're inserting at the end.
  $lastGroup = end($weightOrderedSiblings);
  if (!$lastGroup) {
    return FALSE;
  }
  return new InsertPosition(end($lastGroup), $isNewNode, InsertPosition::DIRECTION_AFTER);
}