Skip to content

Commit

Permalink
Expose compare method, make implicit sort use it
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Stříbrný committed Jun 8, 2017
1 parent 9c56299 commit 1974984
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 36 deletions.
48 changes: 47 additions & 1 deletion src/DateRange.php
Original file line number Diff line number Diff line change
Expand Up @@ -263,4 +263,50 @@ public function equals($b)
$b = static::wrap($b);
return $this->from == $b->from && $this->to == $b->to;
}
}

/**
* @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;
}
}
37 changes: 2 additions & 35 deletions src/DateRangeCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
}

Expand Down Expand Up @@ -194,4 +161,4 @@ public function subtract($subtrahends)

return new static($minuends);
}
}
}

0 comments on commit 1974984

Please sign in to comment.