You are here

public function DateSorter::__invoke in Views XML Backend 8

Sorts a views result.

Parameters

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

Overrides StringSorter::__invoke

File

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

Class

DateSorter
Provides sorting for dates.

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) {
        $a_value = $this
          ->convertToUnixTimestamp(reset($a->{$this->field}));
        $b_value = $this
          ->convertToUnixTimestamp(reset($b->{$this->field}));
        $compare = $a_value - $b_value;
        if ($compare === 0) {
          return $a->index < $b->index ? -1 : 1;
        }
        return $compare;
      });
      break;
    case 'DESC':
      usort($result, function (ResultRow $a, ResultRow $b) {
        $a_value = $this
          ->convertToUnixTimestamp(reset($a->{$this->field}));
        $b_value = $this
          ->convertToUnixTimestamp(reset($b->{$this->field}));
        $compare = $b_value - $a_value;
        if ($compare === 0) {
          return $a->index < $b->index ? -1 : 1;
        }
        return $compare;
      });
      break;
  }
}