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

False positive on DateTime(Immutable) #5259

Closed
Tobion opened this issue Jul 5, 2021 · 7 comments
Closed

False positive on DateTime(Immutable) #5259

Tobion opened this issue Jul 5, 2021 · 7 comments

Comments

@Tobion
Copy link

Tobion commented Jul 5, 2021

Bug report

Phpstan does not seem to understand that there are only two implementations of DateTimeInterface.
The following code

public function __construct(\DateTimeInterface $date)
{
	$this->date = $date instanceof \DateTimeImmutable ? $date : \DateTimeImmutable::createFromMutable($date);
}

results in wrong error

Parameter #1 $object of static method DateTimeImmutable::createFromMutable() expects DateTime, DateTimeInterface given.

Code snippet that reproduces the problem

https://phpstan.org/r/6db83755-bca0-4294-a457-3d38a503aaac

@ondrejmirtes
Copy link
Member

This is expected error, PHPStan does not have hardcoded knowledge there's only two implementations of DateTimeInterface. Use union of the two types instead (in PHPDoc if you're on PHP 7.x): https://phpstan.org/r/0e8fa65d-202a-41d0-9e1e-01941886341a

@Tobion
Copy link
Author

Tobion commented Jul 5, 2021

But I think phpstan should have this hardcoded knowledge. Custom implementations of DateTimeInterface are not possible. False positive errors should be avoided as much as possible because those are hurting phpstan usability the most.

@Tobion
Copy link
Author

Tobion commented Jul 5, 2021

Also changing to union types won't help. The DateTimeInterface is coming from a long chain of other code and even third party code.
So just changing to union types will create a different false positive

Parameter ... of class ... constructor expects DateTime|DateTimeImmutable, DateTimeInterface given.

@Tobion
Copy link
Author

Tobion commented Jul 13, 2021

@ondrejmirtes any chance to reconsider this?

@ondrejmirtes
Copy link
Member

@Tobion I'm not promising PHPStan will understand this in every scenario, but I did a simple fix for your case: phpstan/phpstan-src@5eb96f5

@Tobion
Copy link
Author

Tobion commented Jul 21, 2021

Cool, thank you.

@github-actions
Copy link

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Aug 22, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants