class DateSorter in Views XML Backend 8
Provides sorting for dates.
Hierarchy
- class \Drupal\views_xml_backend\Sorter\StringSorter implements SorterInterface
- class \Drupal\views_xml_backend\Sorter\DateSorter
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\SorterView 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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DateSorter:: |
protected | function | Coverts a value to a UNIX timestamp. | |
DateSorter:: |
public | function |
Sorts a views result. Overrides StringSorter:: |
|
StringSorter:: |
protected | property | The direction to sort. | |
StringSorter:: |
protected | property | The field of the result to sort. | |
StringSorter:: |
public | function | Constructs a StringSorter object. |