You are here

public function OfficeHoursItemList::isOpen in Office Hours 8

Determines if the Entity is Open or Closed.

Parameters

int $time:

Return value

bool Indicator whether the entity is Open or Closed at the given time.

Overrides OfficeHoursItemListInterface::isOpen

File

src/Plugin/Field/FieldType/OfficeHoursItemList.php, line 28

Class

OfficeHoursItemList
Represents an Office hours field.

Namespace

Drupal\office_hours\Plugin\Field\FieldType

Code

public function isOpen($time = NULL) {

  // Loop through all lines.
  // Detect the current line and the open/closed status.
  // Convert the day_number to (int) to get '0' for Sundays, not 'false'.
  $time = $time === NULL ? \Drupal::time()
    ->getRequestTime() : $time;
  $today = (int) idate('w', $time);

  // Get day_number (0=Sun, 6=Sat).
  $now = date('Hi', $time);

  // 'Hi' format, with leading zero (0900).
  $is_open = FALSE;
  foreach ($this
    ->getValue() as $key => $item) {

    // Calculate start and end times.
    $day = (int) $item['day'];

    // 'Hi' format, with leading zero (0900).
    $start = OfficeHoursDatetime::get($item['starthours'], 'Hi');
    $end = OfficeHoursDatetime::get($item['endhours'], 'Hi');
    if ($day - $today == -1 || $day - $today == 6 || $day == strtotime('yesterday midnight')) {

      // We were open yesterday evening, check if we are still open.
      if ($start >= $end && $end > $now) {
        $is_open = TRUE;
      }
    }
    elseif ($day == $today || $day == strtotime('today midnight')) {
      if ($start <= $now) {

        // We were open today, check if we are still open.
        if ($start > $end || $start == $end && !is_null($start) || $start < $end && $end > $now) {
          $is_open = TRUE;
        }
      }
    }
  }
  return $is_open;
}