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 +}