You are here

public function TermWeightWidgetOrderProcessor::sortResults in Facets 8

Orders results and return the new order of results.

Parameters

\Drupal\facets\Result\Result $a: First result which should be compared.

\Drupal\facets\Result\Result $b: Second result which should be compared.

Return value

int -1, 0, or 1 depending which result

Overrides SortProcessorInterface::sortResults

File

src/Plugin/facets/processor/TermWeightWidgetOrderProcessor.php, line 68

Class

TermWeightWidgetOrderProcessor
A processor that orders the term-results by their weight.

Namespace

Drupal\facets\Plugin\facets\processor

Code

public function sortResults(Result $a, Result $b) {

  // Get the term weight once.
  if (!isset($a->termWeight) || !isset($b->termWeight)) {
    $ids = [];
    if (!isset($a->termWeight)) {
      $a_raw = $a
        ->getRawValue();
      $ids[] = $a_raw;
    }
    if (!isset($b->termWeight)) {
      $b_raw = $b
        ->getRawValue();
      $ids[] = $b_raw;
    }
    $entities = $this->entityTypeManager
      ->getStorage('taxonomy_term')
      ->loadMultiple($ids);
    if (!isset($a->termWeight)) {
      if (empty($entities[$a_raw])) {
        return 0;
      }
      $a->termWeight = $entities[$a_raw]
        ->getWeight();
    }
    if (!isset($b->termWeight)) {
      if (empty($entities[$b_raw])) {
        return 0;
      }
      $b->termWeight = $entities[$b_raw]
        ->getWeight();
    }
  }

  // Return the sort value.
  if ($a->termWeight === $b->termWeight) {
    return 0;
  }
  return $a->termWeight < $b->termWeight ? -1 : 1;
}