21

Is there a PHPCS coding standard that would check that proper annotations (@param, @return, @throws, etc.) are present in a docblock, including the proper spacing between them?

hakre
  • 193,403
  • 52
  • 435
  • 836
BenMorel
  • 34,448
  • 50
  • 182
  • 322

3 Answers3

34

Try running the following command and see if it produces what you want:

phpcs /path/to/code --standard=Squiz --sniffs=Squiz.Commenting.FunctionComment,Squiz.Commenting.FunctionCommentThrowTag,Squiz.Commenting.ClassComment,Squiz.Commenting.FileComment,Squiz.Commenting.VariableComment

If it does, you could create your own standard that just includes those sniffs, and anything else you want to check. You do this by creating a ruleset.xml file and using that as your standard.

For example, you could create a file called mystandard.xml and include the following content:

<?xml version="1.0"?>
<ruleset name="MyStandard">
  <description>My custom coding standard.</description>
  <rule ref="Squiz.Commenting.FunctionComment" />
  <rule ref="Squiz.Commenting.FunctionCommentThrowTag" />
  <rule ref="Squiz.Commenting.ClassComment" />
  <rule ref="Squiz.Commenting.FileComment" />
  <rule ref="Squiz.Commenting.VariableComment" />
</ruleset>

Then you can run this command instead:

phpcs /path/to/code --standard=/path/to/mystandard.xml

There are other things you can do in a ruleset.xml file. See the docs here: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-Ruleset

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
Greg Sherwood
  • 6,992
  • 2
  • 29
  • 24
  • 2
    This answer is from 2012. It is still correct. But I would add that today, you can also use the Generic.Commenting.DocComment sniff. These sniffs behave just a little differently, so pick the one that's best for your style. – mkasberg Apr 15 '16 at 18:41
  • Recommend throwing on `-s` to the phpcs argument list; it'll show exact which sniff was triggered by your code, which is useful for debugging and building your rule list. – amphetamachine May 18 '20 at 20:14
9

In 2017 you have now more options:

Tomas Votruba
  • 23,240
  • 9
  • 79
  • 115
0

Disclaimer: I'm author of Rector.

In 2019 you can use static analysis to complete @var types or type declarations for you.

class SomeClass
{
    private $value;

    public setValue(string $string)
    {
        // here we know the string type is assigned
        $this->value = $value;
    }    
}

Knowing that, Rector autocomplete the var type:

class SomeClass
{
    /**
     * @var string
     */
    private $value;

    public setValue(string $string)
    {
        $this->value = $value;
    }    
}

Similar approach works for return type, PHP 7.4 types and type declarations from parent interfaces and classes. All supported by Rector.

Read more in How to Complete Type Declarations without Docblocks with Rector

Tomas Votruba
  • 23,240
  • 9
  • 79
  • 115