You are here

public function NumericSorter::__invoke in Views XML Backend 8

Sorts a views result.

Parameters

\Drupal\views\ResultRow[] &$result: The views result.

Overrides StringSorter::__invoke

File

src/Sorter/NumericSorter.php, line 20
Contains \Drupal\views_xml_backend\Sorter\NumericSorter.

Class

NumericSorter
Provides sorting for numbers.

Namespace

Drupal\views_xml_backend\Sorter

Code

public function __invoke(array &$result) {

  // Notice the order of the subtraction.
  switch ($this->direction) {
    case 'ASC':
      usort($result, function (ResultRow $a, ResultRow $b) {
        $compare = reset($a->{$this->field}) - reset($b->{$this->field});
        if ($compare === 0) {
          return $a->index < $b->index ? -1 : 1;
        }
        return $compare;
      });
      break;
    case 'DESC':
      usort($result, function (ResultRow $a, ResultRow $b) {
        $compare = reset($b->{$this->field}) - reset($a->{$this->field});
        if ($compare === 0) {
          return $a->index < $b->index ? -1 : 1;
        }
        return $compare;
      });
      break;
  }
}