From c2ed6a4cd641b0d008e5d8d9d9292f005a223187 Mon Sep 17 00:00:00 2001 From: Mojmir Fendek Date: Thu, 6 Aug 2020 10:19:03 +1200 Subject: [PATCH] NEW: WithMockTime callback. --- src/ORM/FieldType/DBDatetime.php | 21 +++++++++++++++++++++ tests/php/ORM/DBDatetimeTest.php | 16 ++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/ORM/FieldType/DBDatetime.php b/src/ORM/FieldType/DBDatetime.php index bc0b86e28..d2bf2fd5a 100644 --- a/src/ORM/FieldType/DBDatetime.php +++ b/src/ORM/FieldType/DBDatetime.php @@ -209,6 +209,27 @@ class DBDatetime extends DBDate implements TemplateGlobalProvider self::$mock_now = null; } + /** + * Run a callback with specific time, original mock value is retained after callback + * + * @param DBDatetime|string $time + * @param callable $callback + * @return mixed + * @throws Exception + */ + public static function withFixedNow($time, $callback) + { + $original = self::$mock_now; + + try { + self::set_mock_now($time); + + return $callback(); + } finally { + self::$mock_now = $original; + } + } + public static function get_template_global_variables() { return [ diff --git a/tests/php/ORM/DBDatetimeTest.php b/tests/php/ORM/DBDatetimeTest.php index defb31f9d..aa0a09b26 100644 --- a/tests/php/ORM/DBDatetimeTest.php +++ b/tests/php/ORM/DBDatetimeTest.php @@ -42,6 +42,22 @@ class DBDatetimeTest extends SapphireTest $this->assertEquals($systemDatetime->Date(), $nowDatetime->Date()); } + public function testFixedNow() + { + $mockDate1 = '2010-01-01 10:00:00'; + $mockDate2 = '2011-01-01 10:00:00'; + + DBDatetime::withFixedNow($mockDate1, function () use ($mockDate1, $mockDate2) { + $this->assertEquals($mockDate1, DBDatetime::now()->Rfc2822()); + + DBDatetime::withFixedNow($mockDate2, function () use ($mockDate2) { + $this->assertEquals($mockDate2, DBDatetime::now()->Rfc2822()); + }); + + $this->assertEquals($mockDate1, DBDatetime::now()->Rfc2822()); + }); + } + public function testSetNullAndZeroValues() { $date = DBDatetime::create_field('Datetime', '');