You are here

public function NodeOrderManager::handleListsDecrease in Node Order 8

Reorder list in which the node is dropped.

When a node is removed, recalculates the ordering for a given term ID.

Parameters

int $tid: The term ID.

Overrides NodeOrderManagerInterface::handleListsDecrease

File

src/NodeOrderManager.php, line 319

Class

NodeOrderManager
Defines a service that creates & manages node ordering within taxonomy terms.

Namespace

Drupal\nodeorder

Code

public function handleListsDecrease($tid) {
  $taxonomy_nids = \Drupal::database()
    ->select('taxonomy_index', 'ti')
    ->fields('ti', [
    'nid',
  ])
    ->condition('ti.tid', $tid)
    ->orderBy('ti.weight')
    ->execute()
    ->fetchCol('nid');
  if (!count($taxonomy_nids)) {
    return;
  }
  $weights = $this
    ->getTermMinMax($tid, TRUE);
  $range_border = ceil(count($taxonomy_nids) / 2);

  // Out of range when one of both new list's border weights is corresponding
  // range border.
  $border_out_of_range = $weights['min'] < -$range_border || $weights['max'] > $range_border;
  if ($border_out_of_range) {
    $weight = -$range_border;
    foreach ($taxonomy_nids as $nid) {
      \Drupal::database()
        ->update('taxonomy_index')
        ->fields([
        'weight' => $weight,
      ])
        ->condition('nid', $nid)
        ->condition('tid', $tid)
        ->execute();
      $weight++;
    }

    // Make sure the weight cache is invalidated.
    $this
      ->getTermMinMax($tid, TRUE);
  }
}