1: <?php
2:
3: declare(strict_types=1);
4:
5: /**
6: * This file is part of the Nexus framework.
7: *
8: * (c) John Paul E. Balandan, CPA <paulbalandan@gmail.com>
9: *
10: * For the full copyright and license information, please view
11: * the LICENSE file that was distributed with this source code.
12: */
13:
14: namespace Nexus\Clock\Extension;
15:
16: use Nexus\Clock\Clock;
17: use Nexus\Clock\FrozenClock;
18: use Nexus\Clock\InternalClock;
19: use PHPUnit\Framework\Attributes\After;
20: use PHPUnit\Framework\Attributes\Before;
21:
22: /**
23: * Trait to be used by test cases when mocking the clock.
24: */
25: trait ClockSensitive
26: {
27: private static ?Clock $originalClock = null;
28:
29: #[Before]
30: protected static function saveClock(): void
31: {
32: self::$originalClock = InternalClock::getCurrent();
33: }
34:
35: #[After]
36: protected static function restoreClock(): void
37: {
38: if (null !== self::$originalClock) {
39: InternalClock::set(self::$originalClock);
40: self::$originalClock = null;
41: }
42: }
43:
44: /**
45: * Mocks the current time to a fixed non-moving clock.
46: */
47: private static function mockTime(\DateTimeImmutable|string $mock = 'now', bool $saveClock = true): Clock
48: {
49: if ($saveClock) {
50: self::saveClock();
51: }
52:
53: InternalClock::set(match (true) {
54: $mock instanceof \DateTimeImmutable => new FrozenClock($mock),
55: default => new FrozenClock(new \DateTimeImmutable($mock)),
56: });
57:
58: return InternalClock::getCurrent();
59: }
60: }
61: