Search code examples
phpphpmdphpcs

PHPCS / PHPMD : Is there a PHP Code Sniffer / Mess Detector way to ensure there are docblocks?


Is there a way I can use PHP Code Sniffer and/or PHP Mess Detector to detect if my classes/properties/methods have proper docblocks? For example:

class Foo
{
    protected $bar;

    public function doStuff(){
        // ...
    }
}

The above example should raise red flags. However, the following example should pass:

/**
 * Class Foo
 * @package Vendor\Module
 */
class Foo
{
    /**
     * @var Vendor\Module\Model\Bar
     */
    protected $bar;

    /**
     * This method does stuff
     * @return bool
     */
    public function doStuff(){
        // ...
    }
}

I'm not per definition interested if the docblocks are correct (if the return types match that what is returned), I mean: it would be nice if it also does that, but the first step I want to take is the ensure that the docblocks are present.


Solution

  • The solution from duplicated answer is working for the docblock presence check as well.

    This is my Bar class which has comments:

    <?php
    
    namespace PhpCSTesting;
    
    use stdClass;
    
    /**
     * Class Bar
     */
    class Bar
    {
        /**
         * @var stdClass
         */
        protected $bar;
    
        /**
         * This method does stuff
         *
         * @return boolean
         */
        public function doStuff()
        {
            return true;
        }
    }
    

    When I run the sniffer I get no errors:

    bin/phpcs Bar.php --standard=Squiz --sniffs=Squiz.Commenting.FunctionComment,Squiz.Commenting.FunctionCommentThrowTag,Squiz.Commenting.ClassComment,Squiz.Commenting.VariableComment
    

    This is my Foo class which has no comments:

    <?php
    
    namespace PhpCSTesting;
    
    class Foo
    {
        protected $bar;
    
        public function doStuff()
        {
            return true;
        }
    }
    

    However, when I run the sniffer for this class I get errors:

    bin/phpcs Foo.php --standard=Squiz --sniffs=Squiz.Commenting.FunctionComment,Squiz.Commenting.FunctionCommentThrowTag,Squiz.Commenting.ClassComment,Squiz.Commenting.VariableComment
    
    FILE: /Users/lukas/workspace/Foo.php
    ----------------------------------------------------------------------
    FOUND 3 ERRORS AFFECTING 3 LINES
    ----------------------------------------------------------------------
     5 | ERROR | Missing class doc comment
     7 | ERROR | Missing member variable doc comment
     9 | ERROR | Missing function doc comment
    ----------------------------------------------------------------------
    

    You can update and modify ruleset based on your needs.