Skip to content

[LiveComponent] Add better error message when hydrating dates #1431

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
Feb 21, 2024
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
2 changes: 1 addition & 1 deletion src/LiveComponent/src/LiveComponentHydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ private function hydrateObjectValue(mixed $value, string $className, bool $allow
}

if (null !== $dateFormat) {
return $className::createFromFormat($dateFormat, $value);
return $className::createFromFormat($dateFormat, $value) ?: throw new BadRequestHttpException(sprintf('The model path "%s" was sent invalid date data "%s" or in an invalid format. Make sure it\'s a valid date and it matches the expected format "%s".', $propertyPathForError, $value, $dateFormat));
}

return new $className($value);
Expand Down
28 changes: 28 additions & 0 deletions src/LiveComponent/tests/Integration/LiveComponentHydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1165,6 +1165,34 @@ public function __construct()
}];
}

public function testHydrationWithInvalidDate(): void
{
$this->expectException(BadRequestHttpException::class);
$this->expectExceptionMessage('The model path "createdAt" was sent invalid date data "0" or in an invalid format. Make sure it\'s a valid date and it matches the expected format "Y. m. d.".');

$this->executeHydrationTestCase(function () {
return HydrationTest::create(new class() {
#[LiveProp(writable: true, format: 'Y. m. d.')]
public \DateTime $createdAt;

public function __construct()
{
$this->createdAt = new \DateTime();
}
})
->mountWith([
'createdAt' => new \DateTime('2023-03-05 9:23', new \DateTimeZone('America/New_York')),
])
->assertDehydratesTo([
'createdAt' => '2023. 03. 05.',
])
->userUpdatesProps([
'createdAt' => '0', // <-- invalid date
])
;
});
}

public function testPassingArrayToWritablePropForHydrationIsNotAllowed(): void
{
$component = new class() {
Expand Down