dsewbh5588 2012-04-12 08:35
浏览 33
已采纳

在PHP_CodeSniffer中查找字符串规则

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()
  • 写回答

1条回答 默认 最新

  • dt246813579 2012-04-12 13:38
    关注

    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.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部