DateSorter.php in Views XML Backend 8
File
src/Sorter/DateSorter.php
View source
<?php
namespace Drupal\views_xml_backend\Sorter;
use Drupal\views\ResultRow;
class DateSorter extends StringSorter {
public function __invoke(array &$result) {
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;
}
}
protected function convertToUnixTimestamp($date) {
if (is_numeric($date)) {
return (int) $date;
}
return strtotime($date);
}
}