Skip to content

Commit

Permalink
Merge pull request #32 from slope-it/fix-constructor-with-empty-string
Browse files Browse the repository at this point in the history
  • Loading branch information
asprega committed Feb 9, 2023
2 parents 3a56322 + 922c773 commit 5884616
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/DateTimeMock/DateTimeMock.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ class DateTimeMock extends \DateTime
{
public function __construct(?string $datetime = 'now', ?DateTimeZone $timezone = null)
{
$datetime = $datetime ?? 'now';

parent::__construct($datetime, $timezone);

$isDateTimeStringRelative = $this->isRelativeDateString($datetime);

// Empty string is not accepted by strtotime, which we use below, so normalize to 'now'. By the way, this is
// also equivalent to how original \DateTime treats it.
if ($datetime === '') {
$datetime = 'now';
}

if ($timezone !== null && !$isDateTimeStringRelative) {
// When there's a timezone and the provided date is absolute, the timestamp must be calculated with that
// specific timezone in order to mimic behavior of the original \DateTime (which does not modify time).
Expand Down
10 changes: 10 additions & 0 deletions tests/ClockMockTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ public function test_DateTime_constructor_with_absolute_date_and_timezone()
$this->assertSame('1986-06-05 12:13:14', $absoluteDateTimeWithTimezone->format('Y-m-d H:i:s'));
}

/**
* @see https://github.com/slope-it/clock-mock/issues/31
*/
public function test_DateTime_constructor_with_empty_string()
{
ClockMock::freeze($fakeNow = new \DateTime('1986-06-05 14:26:29.123456'));

$this->assertEquals($fakeNow, new \DateTime('')); // Empty string should behave exactly as "now"
}

/**
* @see https://github.com/slope-it/clock-mock/issues/7
*/
Expand Down

0 comments on commit 5884616

Please sign in to comment.