Skip to content

Commit

Permalink
fix create from format with invalid format (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
niko-38500 committed Aug 21, 2023
1 parent 0de6305 commit 075d605
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/ClockMock.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,15 @@ public static function mock_date_create_immutable_from_format(): callable
// Create an immutable instance starting from the mutable mock, so we don't have to replicate mocking logic.
$mutableDateTime = date_create_from_format($format, $datetime, $timezone);

return new \DateTimeImmutable($mutableDateTime->format('Y-m-d\TH:i:s.u'), $mutableDateTime->getTimezone());
// $mutableDateTime may be false if the format passed to createDateFromFormat() does not match the supplied date string
if (false === $mutableDateTime) {
return false;
}

return new \DateTimeImmutable(
$mutableDateTime->format('Y-m-d\TH:i:s.u'),
$mutableDateTime->getTimezone()
);
};
}

Expand Down
9 changes: 9 additions & 0 deletions tests/ClockMockTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,15 @@ public function test_date_create_immutable_from_format()
$this->assertSame('2022-05-28 12:13:14', $dateTimeFromFormat->format('Y-m-d H:i:s'));
}

public function test_date_create_immutable_from_format_with_invalid_format()
{
ClockMock::freeze(new \DateTimeImmutable('1986-06-05 12:13:14'));

$dateTimeFromFormat = date_create_immutable_from_format('d/m/Y', '2022-05-28');

$this->assertFalse($dateTimeFromFormat);
}

public function test_date_create_from_format_freeze_reset_must_not_use_mock()
{
ClockMock::freeze(new \DateTimeImmutable('1986-06-05 12:13:14'));
Expand Down

0 comments on commit 075d605

Please sign in to comment.