kylekatarnls / business-time

Carbon mixin to handle business days and opening hours
MIT License
297 stars 14 forks source link

Multiple business-hours #56

Closed matteoconsoli closed 1 year ago

matteoconsoli commented 1 year ago

Any tip on how to implement having multiple business hours ?

kylekatarnls commented 1 year ago

Hello,

It's possible to use multiple instance of Spatie\OpeningHours\OpeningHours:

use Spatie\OpeningHours\OpeningHours;

$hours1 = OpeningHours::create([
    'monday'     => ['09:00-12:00', '13:00-18:00'],
]);
$hours2 = OpeningHours::create([
    'monday'     => ['08:00-11:00', '12:00-17:30'],
]);

$date = CarbonImmutable::parse('2022-12-12 08:30');

var_dump($hours1->isOpenAt($date));
var_dump($hours2->isOpenAt($date));

Demo%3B%0Avar_dump(%24hours2-%3EisOpenAt(%24date))%3B%0A)

Most mixin methods match a method with the same name in OpeningHours. Custom holidays added as exceptions would also work. Sadly for the holidays.region ('us-ny', de-national, etc.) it would be a bit more tricky. I don't think it's possible out of the box, but I might extract the calculator from the mixin so it can be run as an instance instead of statically.

kylekatarnls commented 1 year ago

Or you can also have local opening hours scoped to a specific Carbon object:

<?php

use Cmixin\BusinessTime;

BusinessTime::enable([Carbon::class, CarbonImmutable::class]);

$date1 = CarbonImmutable::parse('2022-12-12 08:30');
$date1->setOpeningHours([
    'monday'     => ['09:00-12:00', '13:00-18:00'],
]);

$date2 = CarbonImmutable::parse('2022-12-12 08:30');
$date2->setOpeningHours([
    'monday'     => ['08:00-11:00', '12:00-17:30'],
]);

var_dump($date1->isOpen());
var_dump($date2->isOpen());

Demo%3B%0Avar_dump(%24date2-%3EisOpen())%3B)

kylekatarnls commented 1 year ago

Glad to announce this is now implemented with a dedicated class in 1.12.0

See Schedule class