Skip to content

Commit 04c04ee

Browse files
committed
DateTime: strict setDate() & setTime()
1 parent 97d965d commit 04c04ee

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/Utils/DateTime.php

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

129129

130+
public function setDate(int $year, int $month, int $day): static
131+
{
132+
self::validate($year, $month, $day);
133+
return parent::setDate($year, $month, $day);
134+
}
135+
136+
137+
public function setTime(int $hour, int $minute, int $second = 0, int $microsecond = 0): static
138+
{
139+
self::validate(hour: $hour, minute: $minute, second: $second, microsecond: $microsecond);
140+
return parent::setTime($hour, $minute, $second, $microsecond);
141+
}
142+
143+
130144
/**
131145
* Returns JSON representation in ISO 8601 (used by JavaScript).
132146
*/

tests/Utils/DateTime.strict.phpt

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Utils\DateTime: strictness.
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+
Assert::exception(
16+
fn() => (new DateTime)->setDate(1978, 2, 31),
17+
Nette\InvalidArgumentException::class,
18+
'The date 1978-02-31 is not valid.',
19+
);
20+
21+
22+
Assert::exception(
23+
fn() => (new DateTime)->setTime(0, 60),
24+
Nette\InvalidArgumentException::class,
25+
'Minute value (60) is out of range.',
26+
);

0 commit comments

Comments
 (0)