Skip to content

Commit 14fb75e

Browse files
committed
[LiveComponent] Add better error message when hydrating dates
1 parent 1a4bdc0 commit 14fb75e

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/LiveComponent/src/LiveComponentHydrator.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,7 @@ private function hydrateObjectValue(mixed $value, string $className, bool $allow
518518
}
519519

520520
if (null !== $dateFormat) {
521-
return $className::createFromFormat($dateFormat, $value);
521+
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));
522522
}
523523

524524
return new $className($value);

src/LiveComponent/tests/Integration/LiveComponentHydratorTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1165,6 +1165,34 @@ public function __construct()
11651165
}];
11661166
}
11671167

1168+
public function testHydrationWithInvalidDate(): void
1169+
{
1170+
$this->expectException(BadRequestHttpException::class);
1171+
$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.".');
1172+
1173+
$this->executeHydrationTestCase(function () {
1174+
return HydrationTest::create(new class() {
1175+
#[LiveProp(writable: true, format: 'Y. m. d.')]
1176+
public \DateTime $createdAt;
1177+
1178+
public function __construct()
1179+
{
1180+
$this->createdAt = new \DateTime();
1181+
}
1182+
})
1183+
->mountWith([
1184+
'createdAt' => new \DateTime('2023-03-05 9:23', new \DateTimeZone('America/New_York')),
1185+
])
1186+
->assertDehydratesTo([
1187+
'createdAt' => '2023. 03. 05.',
1188+
])
1189+
->userUpdatesProps([
1190+
'createdAt' => '0', // <-- invalid date
1191+
])
1192+
;
1193+
});
1194+
}
1195+
11681196
public function testPassingArrayToWritablePropForHydrationIsNotAllowed(): void
11691197
{
11701198
$component = new class() {

0 commit comments

Comments
 (0)