kylekatarnls / business-time

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

Specific closed hours #51

Closed yetkinaykan closed 2 years ago

yetkinaykan commented 2 years ago

Hi, thanks for the package.

Is it possible to specify special closing times on the package? For example, can I mark these hours as closed?

25.09.2021 14:00-14:30
25.09.2021 15:00-15:20
25.09.2021 16:20-16:40
kylekatarnls commented 2 years ago

Hi 👋

It's possible using exceptions:

BusinessTime::enable(Carbon::class, [
  // Define a 7/7 and 24/24 week
  'monday' => ['00:00-24:00'],
  'tuesday' => ['00:00-24:00'],
  'wednesday' => ['00:00-24:00'],
  'thursday' => ['00:00-24:00'],
  'friday' => ['00:00-24:00'],
  'saturday' => ['00:00-24:00'],
  'sunday' => ['00:00-24:00'],
  // Add open hours around closed time for each day
  'exceptions' => [
    '2021-09-25' => [
      '00:00-14:00',
      '14:30-15:00',
      '15:20-16:20',
      '16:40-24:00',
    ],
  ],
]);

$date = Carbon::parse('2021-04-01 17:25');

var_dump($date->isOpen()); // true
echo $date->nextClose()."\n"; // 2021-09-25 14:00:00

$date = Carbon::parse('2021-09-25 15:08');

var_dump($date->isOpen()); // false
echo $date->nextOpen()."\n"; // 2021-09-25 15:20:00
kylekatarnls commented 2 years ago

It's not complex, you can easily create the needed exceptions array from your input:

$closedHours = [
  '2021-09-25 14:00-14:30',
  '2021-09-25 15:00-15:20',
  '2021-09-25 16:20-16:40',
];
$exceptions = [];

foreach ($closedHours as $closedHour) {
  [$day, $range] = explode(' ', $closedHour);
  [$start, $end] = explode('-', $range);
  $exceptions[$day] ??= ['00:00-24:00'];
  [$rangeStart, $rangeEnd] = explode('-', array_pop($exceptions[$day]));
  $exceptions[$day][] = "$rangeStart-$start";
  $exceptions[$day][] = "$end-$rangeEnd";
}

BusinessTime::enable(Carbon::class, [
  // Define a 7/7 and 24/24 week
  'monday' => ['00:00-24:00'],
  'tuesday' => ['00:00-24:00'],
  'wednesday' => ['00:00-24:00'],
  'thursday' => ['00:00-24:00'],
  'friday' => ['00:00-24:00'],
  'saturday' => ['00:00-24:00'],
  'sunday' => ['00:00-24:00'],
  // Add open hours around closed time for each day
  'exceptions' =>$exceptions,
]);
cby016 commented 2 years ago

How to add open 24 hours a day should be added to the documentation. I had to go searching through the issues to find it.

kylekatarnls commented 2 years ago

Feel free to submit a pull-request.