Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
acabal opened this issue May 11, 2024 · 0 comments

Comments

@acabal
Copy link

acabal commented May 11, 2024

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
}
?>
acabal referenced this issue in standardebooks/web May 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant