Debian Codegraph @

lib/3rdParty/composer/symfony/clock/Test/ClockSensitiveTrait.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Clock\Test;
13
14 use PHPUnit\Framework\Attributes\After;
15 use PHPUnit\Framework\Attributes\Before;
16 use PHPUnit\Framework\Attributes\BeforeClass;
17 use Symfony\Component\Clock\Clock;
18 use Symfony\Component\Clock\ClockInterface;
19 use Symfony\Component\Clock\MockClock;
20
21 use function Symfony\Component\Clock\now;
22
23 /**
24 * Helps with mocking the time in your test cases.
25 *
26 * This trait provides one self::mockTime() method that freezes the time.
27 * It restores the global clock after each test case.
28 * self::mockTime() accepts either a string (eg '+1 days' or '2022-12-22'),
29 * a DateTimeImmutable, or a boolean (to freeze/restore the global clock).
30 *
31 * @author Nicolas Grekas <[email protected]>
32 */
33 trait ClockSensitiveTrait
34 {
35 public static function mockTime(string|\DateTimeImmutable|bool $when = true): ClockInterface
36 {
37 Clock::set(match (true) {
38 false === $when => self::saveClockBeforeTest(false),
39 true === $when => new MockClock(),
40 $when instanceof \DateTimeImmutable => new MockClock($when),
41 default => new MockClock(now($when)),
42 });
43
44 return Clock::get();
45 }
46
47 /**
48 * @beforeClass
49 *
50 * @before
51 *
52 * @internal
53 */
54 #[Before]
55 #[BeforeClass]
56 public static function saveClockBeforeTest(bool $save = true): ClockInterface
57 {
58 static $originalClock;
59
60 if ($save && $originalClock) {
61 self::restoreClockAfterTest();
62 }
63
64 return $save ? $originalClock = Clock::get() : $originalClock;
65 }
66
67 /**
68 * @after
69 *
70 * @internal
71 */
72 #[After]
73 protected static function restoreClockAfterTest(): void
74 {
75 Clock::set(self::saveClockBeforeTest(false));
76 }
77 }