Introduce new Monday type and turnBackTime function to simplify working with Mondays
[SonOfLokstallBot.git] / src / common.php
index e71dc5a..7a15a6c 100644 (file)
@@ -6,6 +6,48 @@ require_once(AUTOLOAD_PATH);
 use Telegram\Bot\Api as TelegramAPI;
 use Telegram\Bot\Objects\Update as TelegramUpdate;
 
+final class Monday {
+    private $year;
+    private $month;
+    private $season;
+    private $weekNum;
+    private $dayNum;
+
+    public function __construct(
+        int $year,
+        int $month,
+        string $season,
+        int $weekNum,
+        int $dayNum
+    ) {
+        $this->year = $year;
+        $this->month = $month;
+        $this->season = $season;
+        $this->weekNum = $weekNum;
+        $this->dayNum = $dayNum;
+    }
+
+    public function __get($property) {
+        return $this->$property;
+    }
+}
+
+// Returns a the closest previous Monday given a date.
+// weekNumber is 1-5 (mondays in months are considered the start of a week, so if a month has 5 mondays it has 5 weeks)
+// dayNumber is the day of the month
+function turnBackTime(DateTimeImmutable $date) {
+    $y = (int) $date->format('Y');
+    $m = (int) $date->format('n');
+    $d = (int) $date->format('d');
+    return new Monday(
+        getYearWeekBeginsIn($y, $m, $d),
+        getMonthWeekBeginsIn($y, $m, $d),
+        getSeason(getMonthWeekBeginsIn($y, $m, $d)),
+        getWeekNumber($y, $m, $d),
+        getDayNumber($y, $m, $d)
+    );
+}
+
 function getTelegram(): TelegramAPI {
     STATIC $tg;
     return $tg = $tg ?? new TelegramAPI(BOT_TOKEN);