Generic/PHPDocTypes and PSR5/PHPDocTypes: Adds sniffs #469
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.
Description
Adds sniffs for PHPDoc types, both a generic sniff, and one for conformance to the PHP-FIG PSR-5 rules relating to types (using the generic sniff, with different properties set).
PHPStan and Psalm are the two most commonly used PHP type checkers, and phpDocumentor is moving to base it's type handling off PHPStan, while PHPStorm uses Psalm for type checking. My feeling is that types that are accepted by both PHPStan and Psalm are essentially de facto valid PHPDoc types, so the generic checks aim to check that types meet these criteria.
The PSR-5 sniff only checks rules relating to types.
The checker handles all type-related tags (property-*, template, param, return, and var). I think this makes sense, because it's likely that it will be desired to check all types by the same standard.
Type comparisons are performed between PHPDoc types and PHP natives types, where present. It isn't perfect, because the checker is only aware of a single file at a time, and can't recognise global constants, but I think it's fairly good for what it is. It takes account of namespaces, use aliases, and class hierarchies in the current file. While PHPStan and Psalm will do much better checking, they are easiest to set up for code that adheres to OO principles, and may produce spurious errors for code that makes use of require/include(_once), so the type-checking feature of this sniff may be useful in these cases.
The sniff can check for misplaced type tags, except for misplaced var tags. My understanding is that var tags are appropriate where a variable is first declared, which can include an assignment, as a foreach loop variable, or being returned as a pass-by-reference parameter where one wasn't passed in. The sniff doesn't attempt to check this.
I originally wrote this for the Moodle Coding Style project, but I think it may be more broadly useful, so am submitting it here instead.
Suggested changelog entry
Types of changes
PR checklist