PHPCS-在实例化时强制使用类名

时间:2019-02-26 08:48:24

标签: php 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

1 个答案:

答案 0 :(得分:0)

我最终写了自己的嗅探。

当找到new或使用::的静态调用时,它将检查类名

<?php

namespace MySniffs\Sniffs\Classes;

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;

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_CodeSniffer\Files\File $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()
}