Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Frozen clock for testing purposes.
19
 *
20
 * @package    core
21
 * @copyright  2024 Andrew Lyons <andrew@nicols.co.uk>
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 * @property-read \DateTimeImmutable $time The current time of the clock
24
 */
25
class frozen_clock implements \core\clock {
26
    /** @var DateTimeImmutable The next time of the clock */
27
    public DateTimeImmutable $time;
28
 
29
    /**
30
     * Create a new instance of the frozen clock.
31
     *
32
     * @param null|int $time The initial time to use. If not specified, the current time is used.
33
     */
34
    public function __construct(
35
        ?int $time = null,
36
    ) {
37
        if ($time) {
1441 ariadna 38
            // Note that the constructor with time zone does not work when specifying a timestamp,
39
            // so we have to set timezone separately afterward.
40
            $this->time = (new \DateTimeImmutable("@{$time}"))
41
                ->setTimezone(\core_date::get_server_timezone_object());
1 efrain 42
        } else {
1441 ariadna 43
            $this->time = (new \DateTimeImmutable())->setTimezone(\core_date::get_server_timezone_object());
1 efrain 44
        }
45
    }
46
 
47
    public function now(): \DateTimeImmutable {
48
        return $this->time;
49
    }
50
 
51
    public function time(): int {
52
        return $this->time->getTimestamp();
53
    }
54
 
55
    /**
56
     * Set the time of the clock.
57
     *
58
     * @param int $time
59
     */
60
    public function set_to(int $time): void {
1441 ariadna 61
        $this->time = (new \DateTimeImmutable("@{$time}"))
62
            ->setTimezone(\core_date::get_server_timezone_object());
1 efrain 63
    }
64
 
65
    /**
66
     * Bump the time by a number of seconds.
67
     *
68
     * @param int $seconds
69
     */
70
    public function bump(int $seconds = 1): void {
71
        $this->time = $this->time->modify("+{$seconds} seconds");
72
    }
73
}