Skip to content

Safe\DateTime[Immutable] constructor with no parameters flagged as throwing an exception in PHPStan #53

Open
@acabal

Description

@acabal

Environment

PHP version: 8.1.28
PHPStan version: 1.10.67
Safe version: 2.5.0
PHPStan Safe Rule version: 1.2.0

Description of problem

When PHPStan is configured with missingCheckedExceptionInThrows: true, and the Safe library is used along with Safe's PHPStan rules, a function that creates a new Safe\DateTime[Immutable] object with no parameters makes PHPStan think that the function must be documented as throwing an \Exception.

But, the DateTime[Immutable] class never throws an exception when constructed with no parameters. PHPStan understands this with the base \DateTime[Immutable] constructor and doesn't emit a warning in that case, but it doesn't understand the Safe\DateTime[Immutable] constructor, and emits an erroneous warning.

This is less of an issue with PHP 8.3, because in 8.3 DateTime emits a more specific \DateMalformedStringException and we can configure PHPStan to ignore that. But, previous versions of PHP will still be in use for many years on LTS systems, so this would be worth fixing now.

A workaround is to use a special inline PHPDoc every time we instantiate a new Safe\DateTime with no parameters. Not the worst thing, but it's cluttered and tedious.

Example

PHPStan configuration

parameters:
    exceptions:
        missingCheckedExceptionInThrows: true

PHP

<?php
function test(): void{
	$ts = new Safe\DateTimeImmutable(); // Error - PHPStan emits: Function test() throws checked exception Exception but it's missing from the PHPDoc @throws tag.

	/** @throws void */
	$ts = new Safe\DateTimeImmutable(); // OK, got expected output - PHPStan emits no warning

	$ts = new \DateTimeImmutable(); // OK, got expected output - PHPStan emits: Class DateTimeImmutable is unsafe to use
}
?>

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions