summaryrefslogtreecommitdiffstats
path: root/modules-available/locations/inc/openingtimes.inc.php
blob: 74dae7c3f2b0771c144b003b2d6f8b5a3bbf25e3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php

class OpeningTimes
{

	/**
	 * Get opening times for given location.
	 * Format is the decoded JSON from DB column, i.e. currently a list of entries:
	 * <pre>{
	 * "days": ["Monday", "Tuesday", ...],
	 * "openingtime": "8:00",
	 * "closingtime": "20:00"
	 * }</pre>
	 */
	public static function forLocation(int $locationId): ?array
	{
		static $openingTimesList = false;
		if ($openingTimesList === false) {
			$openingTimesList = Database::queryKeyValueList("SELECT locationid, openingtime FROM location
				WHERE openingtime IS NOT NULL");
		}
		$chain = Location::getLocationRootChain($locationId);
		foreach ($chain as $lid) {
			if (isset($openingTimesList[$lid])) {
				if (is_string($openingTimesList[$lid])) {
					$openingTimesList[$lid] = json_decode($openingTimesList[$lid], true);
				}
				return $openingTimesList[$lid];
			}
		}
		return null;
	}

	/**
	 * Check whether given location is open according to openingtimes.
	 * @param int $locationId location
	 * @param int $openOffsetMin offset to apply to opening times when checking. this is subtracted from opening time
	 * @param int $closeOffsetMin offset to apply to closing times when checking. this is added to closing time
	 */
	public static function isRoomOpen(int $locationId, int $openOffsetMin = 0, int $closeOffsetMin = 0): bool
	{
		$openingTimes = self::forLocation($locationId);
		if ($openingTimes === null)
			return true; // No opening times should mean room is always open
		$now = time();
		$today = date('l', $now);
		foreach ($openingTimes as $row) {
			foreach ($row['days'] as $day) {
				if ($day !== $today)
					continue; // Not today!
				if (strtotime("today {$row['openingtime']} -$openOffsetMin minutes") > $now)
					continue;
				if (strtotime("today {$row['closingtime']} +$closeOffsetMin minutes") < $now)
					continue;
				// Bingo!
				return true;
			}
		}
		return false;
	}

}