Skip to content

Commit f58515d

Browse files
committed
DateTime: strict constructor, setDate(), setTime()
1 parent 847aa7c commit f58515d

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/Utils/DateTime.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,30 @@ 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+
140+
public function setDate(int $year, int $month, int $day): static
141+
{
142+
self::validate($year, $month, $day);
143+
return parent::setDate($year, $month, $day);
144+
}
145+
146+
147+
public function setTime(int $hour, int $minute, int $second = 0, int $microsecond = 0): static
148+
{
149+
self::validate(hour: $hour, minute: $minute, second: $second, microsecond: $microsecond);
150+
return parent::setTime($hour, $minute, $second, $microsecond);
151+
}
152+
153+
130154
/**
131155
* Returns JSON representation in ISO 8601 (used by JavaScript).
132156
*/

tests/Utils/DateTime.strict.phpt

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Utils\DateTime: strict.
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\Utils\DateTime;
10+
use Tester\Assert;
11+
12+
require __DIR__ . '/../bootstrap.php';
13+
14+
15+
date_default_timezone_set('Europe/Prague');
16+
17+
18+
Assert::exception(
19+
fn() => new DateTime('1978-02-31'),
20+
Nette\InvalidArgumentException::class,
21+
"The parsed date was invalid '1978-02-31'",
22+
);
23+
24+
25+
Assert::exception(
26+
fn() => (new DateTime)->setDate(1978, 2, 31),
27+
Nette\InvalidArgumentException::class,
28+
'The date 1978-02-31 is not valid.',
29+
);
30+
31+
32+
Assert::exception(
33+
fn() => (new DateTime)->setTime(0, 60),
34+
Nette\InvalidArgumentException::class,
35+
'Minute value (60) is out of range.',
36+
);

0 commit comments

Comments
 (0)