Skip to content

Commit 2e0aefc

Browse files
committed
DateTime: strict constructor [WIP]
problem with Nette\Database and 0000-00-00
1 parent 04c04ee commit 2e0aefc

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/Utils/DateTime.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,16 @@ public static function validate(
127127
}
128128

129129

130+
public function __construct(string $datetime = 'now', ?\DateTimeZone $timezone = null)
131+
{
132+
parent::__construct($datetime, $timezone);
133+
$errors = self::getLastErrors();
134+
if ($errors && $errors['warnings']) {
135+
throw new Nette\InvalidArgumentException(Arrays::first($errors['warnings']) . " '$datetime'");
136+
}
137+
}
138+
139+
130140
public function setDate(int $year, int $month, int $day): static
131141
{
132142
self::validate($year, $month, $day);

tests/Utils/DateTime.strict.phpt

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,24 @@ use Tester\Assert;
1212
require __DIR__ . '/../bootstrap.php';
1313

1414

15+
Assert::exception(
16+
fn() => new DateTime('1978-02-31'),
17+
Nette\InvalidArgumentException::class,
18+
"The parsed date was invalid '1978-02-31'",
19+
);
20+
21+
Assert::exception(
22+
fn() => new DateTime('0000-00-00'),
23+
Nette\InvalidArgumentException::class,
24+
"The parsed date was invalid '1978-02-31'",
25+
);
26+
1527
Assert::exception(
1628
fn() => (new DateTime)->setDate(1978, 2, 31),
1729
Nette\InvalidArgumentException::class,
1830
'The date 1978-02-31 is not valid.',
1931
);
2032

21-
2233
Assert::exception(
2334
fn() => (new DateTime)->setTime(0, 60),
2435
Nette\InvalidArgumentException::class,

0 commit comments

Comments
 (0)