Search code examples
phppropertiestokenphpcodesniffersniffer

PHP CodeSniffer property not recognized


my sniff doesn't work and doesn't recognize the property private $testvar. I want to make a Doc-Block mandatory there.

When I run code sniffer, the process method doesn't seem to be used. I added some echos there before.

Does the token T_PROPERTY exist? I cannot find it on php manual http://php.net/manual/en/tokens.php Yet, in the squiz lab source code T_PROPERTY is used.

<?php
/**
 * Extension for the pear class comment sniff.
 *
 */

/**
 * Extension for the pear class comment sniff.
 *
 */
class XYZ_Sniffs_Commenting_PropertyCommentSniff implements PHP_CodeSniffer_Sniff
{
    private $testvar = 1;

    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return array(T_PROPERTY);
    }

    /**
     * Checks the property comments.
     *
     * @param PHP_CodeSniffer_File $phpcsFile the file object
     * @param int                  $stackPtr  the stack pointer
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        $find   = PHP_CodeSniffer_Tokens::$scopeModifiers;
        $find[] = T_WHITESPACE;
        $find[] = T_STATIC;

        $commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true);

        if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG
            && $tokens[$commentEnd]['code'] !== T_COMMENT
        ) {
            $phpcsFile->addError('Missing property doc comment', $stackPtr, 'Missing');
            $phpcsFile->recordMetric($stackPtr, 'Function has property comment', 'no');
            return;
        } else {
            $phpcsFile->recordMetric($stackPtr, 'Function has property comment', 'yes');
        }
    }
}

Thanks for your help :).


Solution

  • The T_PROPERTY token is only used when checking JavaScript files. It doesn't exist for PHP files.

    For PHP files, you'll want to use the AbstractVariableSniff helper. Here is a sniff that checks comments of member vars: https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/Commenting/VariableCommentSniff.php

    Notice how it extends PHP_CodeSniffer_Standards_AbstractVariableSniff and then only implements the processMemberVar() method. It leaves the processVariable() and processVariableInString() methods empty because it doesn't care about regular variables inside the code.

    Also note that if you are writing commenting sniffs, the comment parser is completely different in the 2.0 version (currently in beta but due to go stable any week now). Take a look at the new version of the above sniff here: https://github.com/squizlabs/PHP_CodeSniffer/blob/phpcs-fixer/CodeSniffer/Standards/Squiz/Sniffs/Commenting/VariableCommentSniff.php