PHPCS-实例化时强制执行类名情况



我正在使用phpcs检查我的类名称与规则PEAR.NamingConventions.ValidClassName

有效

它在类声明上正常工作:

class My_Class {} // Valid
class My_class {} // Invalid - expected behaviour

是否有任何规则可以在实例化中检查类名称?

new My_class() // Should complain about invalid class name
My_class::someMethod() // Should complain too

我最终写了自己的嗅觉。

当找到new或使用::

的静态调用时,它会检查类名称
<?php
namespace MySniffsSniffsClasses;
use PHP_CodeSnifferSniffsSniff;
use PHP_CodeSnifferFilesFile;
class MySniffs_Sniffs_Classes_ConsistentClassNameCaseSniff implements Sniff
{
    /**
     * Returns the token types that this sniff is interested in.
     *
     * @return array(int)
     */
    public function register() {
        return array(T_NEW, T_DOUBLE_COLON);
    }//end register()

    /**
     * Processes this sniff, when one of its tokens is encountered.
     *
     * @param PHP_CodeSnifferFilesFile $phpcsFile The current file being checked.
     * @param int                         $stackPtr  The position of the current token in the
     *                                               stack passed in $tokens.
     *
     * @return void
     */
    public function process(File $phpcsFile, $stackPtr) {
        $tokens = $phpcsFile->getTokens();
        $token = $tokens[$stackPtr];
        if ($token['type'] === 'T_NEW') {
            $className = $phpcsFile->findNext(T_STRING, $stackPtr);
        } elseif ($token['type'] === 'T_DOUBLE_COLON') {
            $className = $phpcsFile->findPrevious(T_STRING, $stackPtr);
        }
        $name = trim($tokens[$className]['content']);
        $words = explode('_', $name);
        foreach ($words as $word) {
            if (!preg_match("/^[A-Z]/", $word)) {
                $phpcsFile->addError(
                    'Invalid class name case : ' . $name,
                    $stackPtr,
                    'ClassNameCase',
                    array('message' => 'Boom')
                );
            }
        }
    }//end process()
}

相关内容

最新更新