/** * Create a DayInterface object from an array. * * @param array $data The day data. * @return DayInterface */ public static function fromAssociativeArray(array $data) { if (!isset($data['openingIntervals']) || !is_array($data['openingIntervals']) || !isset($data['dayOfWeek'])) { throw new \InvalidArgumentException('Array is not valid.'); } $openingIntervals = array(); foreach ($data['openingIntervals'] as $openingInterval) { $start = TimeBuilder::fromArray($openingInterval['start']); $end = TimeBuilder::fromArray($openingInterval['end']); if (self::isIntervalAllDay($start, $end)) { return new AllDay($data['dayOfWeek']); } $openingIntervals[] = new TimeInterval($start, $end); } return new Day($data['dayOfWeek'], $openingIntervals); }
/** * Create a new BusinessHours with a different timezone from an existing BusinessHours. * * @param BusinessHours $businessHours The original business hours. * @param \DateTimeZone $newTimezone The new timezone. * @return BusinessHours */ public static function shiftToTimezone(BusinessHours $businessHours, \DateTimeZone $newTimezone) { $now = new \DateTime('now'); $oldTimezone = $businessHours->getTimezone(); $offset = $newTimezone->getOffset($now) - $oldTimezone->getOffset($now); if ($offset === 0) { return clone $businessHours; } $tmpDays = array_fill_keys(Day::getDaysOfWeek(), array()); foreach ($businessHours->getDays() as $day) { foreach ($day->getOpeningHoursIntervals() as $interval) { $start = $interval->getStart()->toSeconds() + $offset; $end = $interval->getEnd()->toSeconds() + $offset; // Current day. if ($start < 86400 && $end > 0) { $startForCurrentDay = max($start, 0); $endForCurrentDay = min($end, 86400); $dayOfWeek = $day->getDayOfWeek(); $interval = new TimeInterval(TimeBuilder::fromSeconds($startForCurrentDay), TimeBuilder::fromSeconds($endForCurrentDay)); array_push($tmpDays[$dayOfWeek], $interval); } // Previous day. if ($start < 0) { $startForPreviousDay = 86400 + $start; $endForPreviousDay = min(86400, 86400 + $end); $dayOfWeek = self::getPreviousDayOfWeek($day->getDayOfWeek()); $interval = new TimeInterval(TimeBuilder::fromSeconds($startForPreviousDay), TimeBuilder::fromSeconds($endForPreviousDay)); array_push($tmpDays[$dayOfWeek], $interval); } // Next day. if ($end > 86400) { $startForNextDay = max(0, $start - 86400); $endForNextDay = $end - 86400; $dayOfWeek = self::getNextDayOfWeek($day->getDayOfWeek()); $interval = new TimeInterval(TimeBuilder::fromSeconds($startForNextDay), TimeBuilder::fromSeconds($endForNextDay)); array_push($tmpDays[$dayOfWeek], $interval); } } } $tmpDays = array_filter($tmpDays); $days = self::flattenDaysIntervals($tmpDays); return new BusinessHours($days, $newTimezone); }