Question

I wish to scan files for the string Firebug, but this is not enought. I also wish to make a difference between QFirebug::log and QFirebug::error static methods.

How I can I extract the method name after the class name ?

public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
    $tokens = $phpcsFile->getTokens();
    echo $tokens[$stackPtr]['content'];
    if ($tokens[$stackPtr]['content'] === 'Firebug') {
        $error = 'found ' . $tokens[$stackPtr]['content'];
        $data  = array(trim($tokens[$stackPtr]['content']));
        $phpcsFile->addError($error, $stackPtr, 'Found', $data);
    }

}//end process()
Was it helpful?

Solution

If you run phpcs with the -vv command line argument, you can see a list of tokens that the PHP file is broken into. For a line like Firebug::error(); you get:

Process token 1 on line 2 [lvl:0;]: T_STRING => Firebug
Process token 2 on line 2 [lvl:0;]: T_DOUBLE_COLON => ::
Process token 3 on line 2 [lvl:0;]: T_STRING => error
Process token 4 on line 2 [lvl:0;]: T_OPEN_PARENTHESIS => (
Process token 5 on line 2 [lvl:0;]: T_CLOSE_PARENTHESIS => )
Process token 6 on line 2 [lvl:0;]: T_SEMICOLON => ;

You don't show your whole sniff, but I assume you are looking for the T_STRING token. In this case, once you've determined that $stackPtr is pointing to the "Firebug" sting, just confirm it is a static call and then grab the next string token:

if ($tokens[$stackPtr]['content'] === 'Firebug'
    && $tokens[($stackPtr + 1)]['code'] === T_DOUBLE_COLON
) {
    // This is a static call to a Firebug class method.
    $methodName = $tokens[($stackPtr + 2)]['content'];
    /* your error code here */
}

Or, if you think people are going to put spaces between the double colons, like Firebug :: error() then you can do something like this:

if ($tokens[$stackPtr]['content'] === 'Firebug') {
    // Find the next non-whitespace token.
    $colon = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true);
    if ($tokens[$colon]['code'] === T_DOUBLE_COLON) {
        // This is a static call to a Firebug class method.
        $methodName = $phpcsFile->findNext(T_STRING, ($colon + 1));
        /* your error code here */
    }
}

If you want to go a step further, you can look for the T_OPEN_PARENTHESIS and T_CLOSE_PARENTHESIS tokens as well, to confirm it is a function call, but it depends on the class you are using.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top