我可以使用哪些内置代码来确保括号前和函数名后没有空格

时间:2013-11-22 04:57:43

标签: php codesniffer

是否有内置的嗅探来确保

public function foo () {
                   ^---- 

没有这样的空间。

我无法在任何内置标准中找到它,或者我只是想念它?

1 个答案:

答案 0 :(得分:2)

您可以轻松扩展或创建自己的标准。这是一个示例,说明如何将请求的功能添加到PEAR标准(默认值)。

<?php
//DisallowSpaceBeforeParenthesisSniff.php

class PEAR_Sniffs_Methods_DisallowSpaceBeforeParenthesisSniff implements PHP_CodeSniffer_Sniff
{
    public function register()
    {
        return array(T_FUNCTION);
    }

    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        do {
          $stackPtr++;
          $type = $tokens[$stackPtr]['type'];  
        } while ('T_OPEN_PARENTHESIS' != $type);

        if ('T_WHITESPACE' == $tokens[$stackPtr-1]['type']) {
            $error = 'Spaces before parenthesis and after function name are prohibited. Found: %s';
            $place = $tokens[$stackPtr-2]['content'] . 
                $tokens[$stackPtr-1]['content'] . 
                $tokens[$stackPtr]['content'];
            $error = sprintf($error, $place);
            $phpcsFile->addError($error, $stackPtr-1);
        }
    }
}

以下文件位于:/usr/share/php/PHP/CodeSniffer/Standards/PEAR/Sniffs/Methods

示例:

<?php

// test.php
class abc
{
    public function hello ($world)
    {

    }
}
bernard @ ubuntu:〜/ Desktop $ phpcs test.php

FILE: /home/bernard/Desktop/test.php
--------------------------------------------------------------------------------
FOUND 5 ERROR(S) AFFECTING 2 LINE(S)
--------------------------------------------------------------------------------
 2 | ERROR | Missing file doc comment
 2 | ERROR | Missing class doc comment
 2 | ERROR | Class name must begin with a capital letter
 4 | ERROR | Missing function doc comment
 4 | ERROR | Spaces before parenthesis and after function name are prohibited.
   |       | Found: hello (
--------------------------------------------------------------------------------

我希望这会对你有所帮助