Improving the get method return annotation. #8
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The current return annotation of the
ServiceContainer::getmethod@return T|ServiceContaineris unnecessarily generic - even when a static analyzer (PHPStan, Psalm) is able to recognize the typeT, theServiceContainertype is forced into the result.Ideally
@return Twould be enough (it already includes theT = ServiceContainercase) but it looks like there's an issue in PHPStan that it doesn't seeServiceContaineras a subtype ofTin this case. I've reported the issue at phpstan/phpstan#8756.Until the PHPStan issue is solved, we can use a workaround that utilizes the conditional type declaration (as demonstrated here: https://phpstan.org/r/f2c3eb91-c6b0-45ca-9dd5-d434274f82af).
There's no such issue with Psalm (as shown here: https://psalm.dev/r/85f8d8262c) so I think we should only introduce the workaround with a PHPStan-specific annotation (
@phpstan-return).Also note that Intelephense doesn't recognize templates, so
@return Twon't work well with it too. However, neither did@return T|ServiceContainer. So if we wanted to make it work well even with Intelephense, we should probaly use@return mixed,@psalm-return Tand@phpstan-return (T is static ? static : T).