From 197498439439621cd878483372d0765d829d351f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20St=C5=99=C3=ADbrn=C3=BD?= Date: Thu, 8 Jun 2017 08:43:40 +0200 Subject: [PATCH] Expose compare method, make implicit sort use it --- src/DateRange.php | 48 ++++++++++++++++++++++++++++++++++++- src/DateRangeCollection.php | 37 ++-------------------------- 2 files changed, 49 insertions(+), 36 deletions(-) diff --git a/src/DateRange.php b/src/DateRange.php index 849e6a4..cde58b7 100644 --- a/src/DateRange.php +++ b/src/DateRange.php @@ -263,4 +263,50 @@ public function equals($b) $b = static::wrap($b); return $this->from == $b->from && $this->to == $b->to; } -} \ No newline at end of file + + /** + * @param array|self $a + * @param array|self $b + * @return int + */ + public static function compare($a, $b) + { + $a = static::wrap($a); + $b = static::wrap($b); + + $fromA = $a->getFrom(); + $fromB = $b->getFrom(); + $toA = $a->getTo(); + $toB = $b->getTo(); + + // by from (NULL first) + if (!$fromA && $fromB) { + return -1; + } else if ($fromA && !$fromB) { + return 1; + } else if ($fromA && $fromB) { + // ASC by from + if ($fromA < $fromB) { + return -1; + } else if ($fromA > $fromB) { + return 1; + } + } + + // by to (NULL last) + if (!$toA && $toB) { + return 1; + } else if ($toA && !$toB) { + return -1; + } else if ($toA && $toB) { + // ASC by to + if ($toA < $toB) { + return -1; + } else if ($toA > $toB) { + return 1; + } + } + + return 0; + } +} diff --git a/src/DateRangeCollection.php b/src/DateRangeCollection.php index afcffdc..29ef47e 100644 --- a/src/DateRangeCollection.php +++ b/src/DateRangeCollection.php @@ -20,40 +20,7 @@ public function __construct($collection) } usort($this->ranges, function (DateRange $a, DateRange $b) { - $fromA = $a->getFrom(); - $fromB = $b->getFrom(); - $toA = $a->getTo(); - $toB = $b->getTo(); - - // by from (NULL first) - if (!$fromA && $fromB) { - return -1; - } else if ($fromA && !$fromB) { - return 1; - } else if ($fromA && $fromB) { - // ASC by from - if ($fromA < $fromB) { - return -1; - } else if ($fromA > $fromB) { - return 1; - } - } - - // by to (NULL last) - if (!$toA && $toB) { - return 1; - } else if ($toA && !$toB) { - return -1; - } else if ($toA && $toB) { - // ASC by to - if ($toA < $toB) { - return -1; - } else if ($toA > $toB) { - return 1; - } - } - - return 0; + return DateRange::compare($a, $b); }); } @@ -194,4 +161,4 @@ public function subtract($subtrahends) return new static($minuends); } -} \ No newline at end of file +}