Lines 100.00% 27 / 27
Methods 100.00% 14 / 14
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 runEvery 100.00% 1 / 1 100.00% 1 / 1 1
 runDailyAt 100.00% 1 / 1 100.00% 1 / 1 1
 runOnCron 100.00% 1 / 1 100.00% 1 / 1 1
 runAfter 100.00% 1 / 1 100.00% 1 / 1 1
 runAt 100.00% 1 / 1 100.00% 1 / 1 1
 runAtEntityTime 100.00% 3 / 3 100.00% 1 / 1 1
 runAtSunEvent 100.00% 1 / 1 100.00% 1 / 1 1
 waitFor 100.00% 1 / 1 100.00% 1 / 1 1
 cancelAll 100.00% 2 / 2 100.00% 1 / 1 2
 armElapsedSchedule 100.00% 7 / 7 100.00% 1 / 1 2
 armWallClockSchedule 100.00% 5 / 5 100.00% 1 / 1 2
 armTask 100.00% 1 / 1 100.00% 1 / 1 1
 claimTaskId 100.00% 1 / 1 100.00% 1 / 1 1
34final class ManualScheduler implements Scheduler
35{
36    /** @var list<ScheduledTask> */
37    private array $tasks = [];
38
39    private int $taskCounter = 0;
40
41    public function __construct(
42        private readonly ManualTimers $timers,
43        private readonly SunCalendar $sunCalendar,
44        private readonly HaContext $ha,
45    ) {}
46
47    public function runEvery(Duration $period, Closure $handler): ScheduledTask
48    {
49        return $this->armElapsedSchedule(IntervalSchedule::every($period), $handler);
50    }
51
52    public function runDailyAt(TimeOfDay|string $time, Closure $handler, DayOfWeek ...$onlyOn): ScheduledTask
53    {
54        return $this->armWallClockSchedule(CalendarSchedule::dailyAt($time, ...$onlyOn), $handler);
55    }
56
57    public function runOnCron(string $expression, Closure $handler): ScheduledTask
58    {
59        return $this->armWallClockSchedule(CronSchedule::parse($expression), $handler);
60    }
61
62    public function runAfter(Duration $delay, Closure $handler): ScheduledTask
63    {
64        return $this->armElapsedSchedule(DelaySchedule::after($delay), $handler);
65    }
66
67    public function runAt(DateTimeImmutable $moment, Closure $handler): ScheduledTask
68    {
69        return $this->armWallClockSchedule(OneShotSchedule::fromMoment($moment), $handler);
70    }
71
72    public function runAtEntityTime(EntityId|string $entity, Closure $handler): ScheduledTask
73    {
74        $entityId = EntityId::fromStringOrId($entity);
75        EntityTime::requireSupportedEntity($entityId);
76
77        return $this->tasks[] = new ManualEntityTimeTask($this->claimTaskId(), $entityId, $this->ha, $this->timers->clock, $this->armWallClockSchedule(...), $handler);
78    }
79
80    public function runAtSunEvent(SunEvent $event, Closure $handler, ?SunOffset $offset = null): ScheduledTask
81    {
82        return $this->armWallClockSchedule(SunEventSchedule::forEvent($this->sunCalendar, $event, $offset), $handler);
83    }
84
85    /**
86     * @template T
87     * @param Closure(PendingWait<T>): (Closure(): void) $arm
88     * @return T|null
89     */
90    public function waitFor(Closure $arm, ?Duration $timeout = null): mixed
91    {
92        return $this->timers->waitFor($arm, $timeout);
93    }
94
95    public function cancelAll(): void
96    {
97        foreach ($this->tasks as $task) {
98            $task->cancel();
99        }
100    }
101
102    /** @param Closure(ScheduledRun): void $handler */
103    private function armElapsedSchedule(ElapsedSchedule $schedule, Closure $handler): ScheduledTask
104    {
105        $clock = $this->timers->clock;
106        $anchor = $clock->getMonotonicTime();
107        $anchoredAt = $clock->getNow();
108
109        return $this->armTask(static function (Instant $after) use ($schedule, $anchor, $anchoredAt): ?Instant {
110            $due = $schedule->findNextDueAfter($anchor, $anchor->plus($after->elapsedSince($anchoredAt)));
111
112            return $due === null ? null : $anchoredAt->plus($due->elapsedSince($anchor));
113        }, $handler);
114    }
115
116    /** @param Closure(ScheduledRun): void $handler */
117    private function armWallClockSchedule(WallClockSchedule $schedule, Closure $handler): ScheduledTask
118    {
119        $zone = $this->timers->clock->getTimeZone();
120
121        return $this->armTask(static function (Instant $after) use ($schedule, $zone): ?Instant {
122            $next = $schedule->findNextOccurrenceAfter($after->toDateTime($zone));
123
124            return $next === null ? null : Instant::fromDateTime($next);
125        }, $handler);
126    }
127
128    /**
129     * @param Closure(Instant): ?Instant $findNextRunAfter
130     * @param Closure(ScheduledRun): void $handler
131     */
132    private function armTask(Closure $findNextRunAfter, Closure $handler): ScheduledTask
133    {
134        return $this->tasks[] = new ManualScheduledTask($this->claimTaskId(), $this->timers, $findNextRunAfter, $handler);
135    }
136
137    private function claimTaskId(): string
138    {
139        return 'manual:' . $this->taskCounter++;
140    }
141}