You are here

public static function OfficeHoursDateHelper::hours in Office Hours 8

Gets the (limited) hours of a day.

Mimics DateHelper::hours() function, but that function does not support limiting the hours. The limits are set in the Widget settings form, and used in the Widget form.

Overrides DateHelper::hours

2 calls to OfficeHoursDateHelper::hours()
OfficeHoursItem::storageSettingsForm in src/Plugin/Field/FieldType/OfficeHoursItem.php
Returns a form for the storage-level settings.
OfficeHoursList::processOfficeHoursSlot in src/Element/OfficeHoursList.php
Process an individual element.

File

src/OfficeHoursDateHelper.php, line 166

Class

OfficeHoursDateHelper
Defines lots of helpful functions for use in massaging dates.

Namespace

Drupal\office_hours

Code

public static function hours($format = 'H', $required = FALSE, $start = 0, $end = 23) {
  $hours = [];

  // Get the valid hours. DateHelper API doesn't provide
  // straight method for this.
  $add_midnight = empty($end);

  // midnight.
  $start = empty($start) ? 0 : max(0, (int) $start);
  $end = empty($end) ? 23 : min(23, (int) $end);

  // Begin modified copy from date_hours().
  if ($format == 'h' || $format == 'g') {

    // 12-hour format.
    $min = 1;
    $max = 24;
    for ($i = $min; $i <= $max; $i++) {
      if ($i >= $start && $i <= $end || $end - $start >= 11) {
        $hour = $i <= 12 ? $i : $i - 12;
        $hours[$hour] = $hour < 10 && ($format == 'H' || $format == 'h') ? "0{$hour}" : (string) $hour;
      }
    }
    $hours = array_unique($hours);
  }
  else {
    $min = $start;
    $max = $end;
    for ($i = $min; $i <= $max; $i++) {
      $hour = $i;
      $hours[$hour] = $hour < 10 && ($format == 'H' || $format == 'h') ? "0{$hour}" : (string) $hour;
    }
  }
  if ($add_midnight) {
    $hours[00] = $format == 'H' || $format == 'h' ? "00" : (string) "0";
  }
  $none = [
    '' => '',
  ];
  $hours = !$required ? $none + $hours : $hours;

  // End modified copy from date_hours().
  return $hours;
}