You are here

public function Link::postSave in Colossal Menu 8

Same name and namespace in other branches
  1. 2.x src/Entity/Link.php \Drupal\colossal_menu\Entity\Link::postSave()

Update the link tree.

Overrides ContentEntityBase::postSave

File

src/Entity/Link.php, line 80

Class

Link
Defines the Link entity.

Namespace

Drupal\colossal_menu\Entity

Code

public function postSave(EntityStorageInterface $storage, $update = TRUE) {
  $connection = $this
    ->getConnection();
  if (!$update) {

    // Add the Link to itself.
    $connection
      ->insert('colossal_menu_link_tree')
      ->fields([
      'ancestor' => $this
        ->id(),
      'descendant' => $this
        ->id(),
      'depth' => 0,
    ])
      ->execute();
    if ($this
      ->getParent()) {

      // Get the tree of the link's parent.
      $result = $connection
        ->select('colossal_menu_link_tree', 't')
        ->fields('t', [
        'ancestor',
        'depth',
      ])
        ->condition('t.descendant', $this
        ->getParent()
        ->id())
        ->execute();
      while ($row = $result
        ->fetchObject()) {
        $connection
          ->insert('colossal_menu_link_tree')
          ->fields([
          'ancestor' => $row->ancestor,
          'descendant' => $this
            ->id(),
          'depth' => $row->depth + 1,
        ])
          ->execute();
      }
    }
  }
  else {

    // First get the link's tree below itself.
    $query = $connection
      ->select('colossal_menu_link_tree', 't')
      ->fields('t', [
      'descendant',
      'depth',
    ])
      ->condition('t.ancestor', $this
      ->id());
    $result = $query
      ->execute();
    $descendants = [];
    $ids = [];
    while ($row = $result
      ->fetchObject()) {
      $descendants[] = [
        'descendant' => $row->descendant,
        'depth' => $row->depth,
      ];
      $ids[] = $row->descendant;
    }

    // Then delete the link tree above the current link.
    if (!empty($ids)) {
      $connection
        ->delete('colossal_menu_link_tree')
        ->condition('descendant', $ids, 'IN')
        ->condition('ancestor', $ids, 'NOT IN')
        ->execute();
    }
    if ($this
      ->getParent()) {

      // Finally, copy the tree from the new parent.
      $result = $connection
        ->select('colossal_menu_link_tree', 't')
        ->fields('t', [
        'ancestor',
        'depth',
      ])
        ->condition('t.descendant', $this
        ->getParent()
        ->id())
        ->execute();
      while ($row = $result
        ->fetchObject()) {
        foreach ($descendants as $descendant) {
          $connection
            ->insert('colossal_menu_link_tree')
            ->fields([
            'ancestor' => $row->ancestor,
            'descendant' => $descendant['descendant'],
            'depth' => $row->depth + $descendant['depth'] + 1,
          ])
            ->execute();
        }
      }
    }
  }
  return parent::postSave($storage, $update);
}