Search code examples
phpphpcs

PHPCS - Enforce class name case when instantiating


I'm using PHPCS to check my class name are valid with the rule PEAR.NamingConventions.ValidClassName

It works fine on class declaration:

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

Is there any rule to check class name at instantiation?

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

Solution

  • I ended up writing my own sniff.

    It checks class name when it finds a new or a static call with ::

    <?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()
    }