Skip to content

Fix DateTimeImmutable::createFromInterface error #402

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lib/DateTimeImmutable.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,16 @@ public static function createFromMutable($dateTime): self
return self::createFromRegular($date);
}

public static function createFromInterface(\DateTimeInterface $object): self
{
if ($object instanceof \DateTime) {
$object = self::createFromMutable($object);
} elseif ($object instanceof DateTimeImmutable) {
$object = $object->getInnerDateTime();
}
return self::createFromRegular($object);
}

/**
* @param mixed[] $array
* @return DateTimeImmutable
Expand Down
20 changes: 20 additions & 0 deletions tests/DateTimeImmutableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,24 @@ public function testCreateFromMutable(): void

self::assertSame($safeDate->format(\DateTimeInterface::ATOM), $safeImmutableDate->format(\DateTimeInterface::ATOM));
}

/**
* @dataProvider createFromInterfaces
*/
public function testCreateFromInterface(\DateTimeInterface $dateTime): void
{
$safeImmutableDate = \Safe\DateTimeImmutable::createFromInterface($dateTime);

self::assertSame($dateTime->format(\DATE_ATOM), $safeImmutableDate->format(\DATE_ATOM));
}

public function createFromInterfaces(): array
{
return [
[new \DateTime('2022-11-29T14:17:34+00:00')],
[new \Safe\DateTime('2022-11-29T14:17:34+00:00')],
[new \DateTimeImmutable('2022-11-29T14:17:34+00:00')],
[new \Safe\DateTimeImmutable('2022-11-29T14:17:34+00:00')],
];
}
}