You are here

class DateSorter in Views XML Backend 8

Provides sorting for dates.

Hierarchy

Expanded class hierarchy of DateSorter

4 files declare their use of DateSorter
Date.php in src/Plugin/views/sort/Date.php
Contains \Drupal\views_xml_backend\Plugin\views\sort\Date.
Date.php in src/Plugin/views/field/Date.php
Contains \Drupal\views_xml_backend\Plugin\views\field\Date.
DateSorterTest.php in tests/src/Unit/Sorter/DateSorterTest.php
DateTest.php in tests/src/Unit/Plugin/views/sort/DateTest.php
Contains \Drupal\Tests\views_xml_backend\Unit\Plugin\views\sort\DateTest.

File

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

Namespace

Drupal\views_xml_backend\Sorter
View source
class DateSorter extends StringSorter {

  /**
   * {@inheritdoc}
   */
  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;
    }
  }

  /**
   * Coverts a value to a UNIX timestamp.
   *
   * @param string|int $date
   *   The date to convert.
   *
   * @return int
   *   The unix timestamp of the date.
   */
  protected function convertToUnixTimestamp($date) {
    if (is_numeric($date)) {
      return (int) $date;
    }
    return strtotime($date);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DateSorter::convertToUnixTimestamp protected function Coverts a value to a UNIX timestamp.
DateSorter::__invoke public function Sorts a views result. Overrides StringSorter::__invoke
StringSorter::$direction protected property The direction to sort.
StringSorter::$field protected property The field of the result to sort.
StringSorter::__construct public function Constructs a StringSorter object.