Include date in currentOpenRange
Joseph-Cardwell opened this issue · comments
This actually a feature request:
In my case I'm trying to highlight the portion of the day that is open. If the date was included for currentOpenRange I could use that to compare to current date to know that current open hours are after midnight hours for previous day.
By adding a default false parameter to currentOpenRange for 'include date' the function is backwards compatible.
If this makes sense I will create a pull request.
Hello,
Actually, it's not a big deal to know the ->start()
is on the previous day. start day = start > end ? day - 1 : day
$openingHours = \Spatie\OpeningHours\OpeningHours::create([
'overflow' => true,
'friday' => ['20:00-03:00'],
'saturday' => ['20:00-03:00'],
], null);
$now = new DateTimeImmutable('now'); // Or any date
$range = $openingHours->currentOpenRange($now);
if ($range) {
$start = $now->modify($range->start() . ($range->start() > $range->end() ? ' - 1 day' : ''));
$end = $now->modify($range->end());
echo "It's open since ".$start->format('Y-m-d H:i')."\n";
echo "It will close at ".$end->format('Y-m-d H:i')."\n";
}
I think an extra boolean parameter (which also breaks the principle of single responsibility: https://phpmd.org/rules/cleancode.html#booleanargumentflag) is not ideal. Mostly because of the typing. The method currently return TimeRange|false
and TimeRange
does not contain the date information, so the method would need to return an other kind of object or an array.
But eventually it could be an extra method currentOpenRangeDates()
I will finally rethink this for the next major version, but for 2.x version, the currentOpenRangeStart
and currentOpenRangeEnd
are enough for this purpose:
$openingHours = \Spatie\OpeningHours\OpeningHours::create([
'overflow' => true,
'friday' => ['20:00-03:00'],
'saturday' => ['20:00-03:00'],
], null);
$now = new DateTimeImmutable('now'); // Or any date
$start = $openingHours->currentOpenRangeStart($now);
if ($start) {
$end = $openingHours->currentOpenRangeEnd($now);
echo "It's open since ".$start->format('Y-m-d H:i')."\n";
echo "It will close at ".$end->format('Y-m-d H:i')."\n";
}
So I will for now avoid adding methods and close this.
Or a last alternative with isOpenAt
, previousOpen
and nextClose
which has the advantage you can easily flip the code for closed ranges:
$openingHours = \Spatie\OpeningHours\OpeningHours::create([
'overflow' => true,
'friday' => ['20:00-03:00'],
'saturday' => ['20:00-03:00'],
], null);
$now = new DateTimeImmutable('2020-09-25 21:34'); // Or any date
if ($openingHours->isOpenAt($now)) {
echo "It's open since ".$openingHours->previousOpen($now)->format('Y-m-d H:i')."\n";
echo "It will close at ".$openingHours->nextClose($now)->format('Y-m-d H:i')."\n";
}