Skip to content

Commit

Permalink
added a test to document the bug and methods to work around it
Browse files Browse the repository at this point in the history
  • Loading branch information
Kharhamel committed Sep 2, 2020
1 parent aa7aae7 commit 8d2269c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
31 changes: 31 additions & 0 deletions generator/tests/DateTimeImmutableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,35 @@ public function testEquals(): void
$this->assertEquals($phpDateTime, $safeDateTime2);
$this->assertEquals($safeDateTime1, $safeDateTime2);
}

//DatePeriod corrupts our DateTimeImmutable by setting their inner to null.
//This bug cannot be solved without editing DatePeriod itself.
public function testDatePeriodBug(): void
{
$start = new \Safe\DateTimeImmutable('2020-01-01');
$end = (new \Safe\DateTimeImmutable('2020-01-03'))->modify('+1 day');
$datePeriod = new \DatePeriod($start, new \DateInterval('P1D'), $end);

/** @var DateTimeImmutable $date */
foreach ($datePeriod as $date) {
$this->expectException(\TypeError::class);
$this->assertNull($date->getInnerDateTime());
}

}

public function testSwitchBetweenRegularAndSafe(): void
{
$d = new \DateTimeImmutable('2019-01-01');
$d2 = \Safe\DateTimeImmutable::createFromRegular($d);
$d3 = $d2->getInnerDateTime();
$this->assertSame($d->format('Y-m-d H:i:s.u'), $d3->format('Y-m-d H:i:s.u'));
}

public function testSwitchBetweenRegularAndSafe2(): void
{
$d = new \Safe\DateTimeImmutable('2019-01-01');
$d2 = \Safe\DateTimeImmutable::createFromRegular($d->getInnerDateTime());
$this->assertSame($d->format('Y-m-d H:i:s.u'), $d2->format('Y-m-d H:i:s.u'));
}
}
12 changes: 9 additions & 3 deletions lib/DateTimeImmutable.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,20 @@ public function __construct($time = 'now', $timezone = null)
$this->innerDateTime = new parent($time, $timezone);
}

//switch from regular datetime to safe version
private static function createFromRegular(\DateTimeImmutable $datetime): self
//switch between regular datetime and safe version
public static function createFromRegular(\DateTimeImmutable $datetime): self
{
$safeDatetime = new self($datetime->format('Y-m-d H:i:s.u'), $datetime->getTimezone()); //we need to also update the wrapper to not break the operators '<' and '>'
$safeDatetime->innerDateTime = $datetime;
$safeDatetime->innerDateTime = $datetime; //to make sure we don't lose information because of the format().
return $safeDatetime;
}

//usefull if you need to switch back to regular DateTimeImmutable (for example when using DatePeriod)
public function getInnerDateTime(): \DateTimeImmutable
{
return $this->innerDateTime;
}

/////////////////////////////////////////////////////////////////////////////
// overload functions with false errors

Expand Down

0 comments on commit 8d2269c

Please # to comment.