diff --git a/lib/DateTime.php b/lib/DateTime.php index 56eb809f..1d62aeae 100644 --- a/lib/DateTime.php +++ b/lib/DateTime.php @@ -39,8 +39,10 @@ public static function createFromFormat($format, $time, $timezone = null): self */ public function diff($datetime2, $absolute = false): DateInterval { + // in PHP <8.3 this returns false, 8.3 onwards throw an exception, + // phpstan is can't seem to comprehend both at once? /** @var \DateInterval|false $result */ - $result = parent::diff($datetime2, $absolute); + $result = parent::diff($datetime2, $absolute); // @phpstan-ignore-line if ($result === false) { throw DatetimeException::createFromPhpError(); } @@ -52,27 +54,13 @@ public function diff($datetime2, $absolute = false): DateInterval * @return DateTime Returns the DateTime object for method chaining. * @throws DatetimeException */ + #[\ReturnTypeWillChange] public function modify($modify): self { + // in PHP <8.3 this returns false, 8.3 onwards throw an exception, + // phpstan is can't seem to comprehend both at once? /** @var DateTime|false $result */ - $result = parent::modify($modify); - if ($result === false) { - throw DatetimeException::createFromPhpError(); - } - return $result; - } - - /** - * @param int $year - * @param int $month - * @param int $day - * @return DateTime - * @throws DatetimeException - */ - public function setDate($year, $month, $day): self - { - /** @var DateTime|false $result */ - $result = parent::setDate($year, $month, $day); + $result = parent::modify($modify); // @phpstan-ignore-line if ($result === false) { throw DatetimeException::createFromPhpError(); } diff --git a/tests/DateTimeTest.php b/tests/DateTimeTest.php index 69c8a246..ba818aae 100644 --- a/tests/DateTimeTest.php +++ b/tests/DateTimeTest.php @@ -24,18 +24,6 @@ public function testCreateFromFormatPreserveTimeAndTimezone(): void $this->assertEquals($timezone, $datetime->getTimezone()); } - public function testSetDate(): void - { - $datetime = new \Safe\DateTime(); - $datetime = $datetime->setDate(2017, 4, 6); - $this->assertInstanceOf(DateTime::class, $datetime); - $this->assertEquals(2017, $datetime->format('Y')); - $this->assertEquals(4, $datetime->format('n')); - $this->assertEquals(6, $datetime->format('j')); - - //todo: test an error case - } - public function testModify(): void { $datetime = new \Safe\DateTime(); @@ -44,4 +32,13 @@ public function testModify(): void $this->assertInstanceOf(DateTime::class, $datetime); $this->assertEquals('7-4-2017', $datetime->format('j-n-Y')); } + + public function testModifyThrowsExceptionOnInvalidInput(): void + { + // In php 8.1/8.2 this is \Safe\DatetimeException + // In php 8.3+ this is \DateMalformedStringException + // TODO: find some way to get phpstan to check the above + $this->expectException(\Throwable::class); + (new \Safe\DateTime())->modify('invalid date'); + } }