Problem/Motivation

For example:

Filename: Foo.php, while class name in Foo.php: FOo or foo, fOO etc.

Proposed resolution

https://github.com/pfrenssen/coder/pull/100

Remaining tasks

User interface changes

API changes

Data model changes

Release notes snippet

Comments

jungle created an issue. See original summary.

jungle’s picture

Title: Add a sniff to fix class name or interface name not identical » Add a sniff to fix class name or interface name not identical with the filename
jungle’s picture

Issue summary: View changes
Status: Active » Needs review
klausi’s picture

Status: Needs review » Postponed (maintainer needs more info)

I think we already have this sniff in ClassFileNameSniff. Can you check and use that one?

jungle’s picture

Status: Postponed (maintainer needs more info) » Needs review
 public function process(File $phpcsFile, $stackPtr)
    {
        // This check only applies to Drupal 8+, in Drupal 7 we can have classes
        // in all kinds of files.
        if (Project::getCoreVersion($phpcsFile) < 8) {
            return ($phpcsFile->numTokens + 1);
        }

        $fullPath = basename($phpcsFile->getFilename());
        $fileName = substr($fullPath, 0, strrpos($fullPath, '.'));
        if ($fileName === '') {
            // No filename probably means STDIN, so we can't do this check.
            return ($phpcsFile->numTokens + 1);
        }

        // If the file is not a php file, we do not care about how it looks,
        // since we care about psr-4.
        $extension = pathinfo($fullPath, PATHINFO_EXTENSION);
        if ($extension !== 'php') {
            return ($phpcsFile->numTokens + 1);
        }

        $tokens  = $phpcsFile->getTokens();
        $decName = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);

        if ($tokens[$decName]['code'] === T_STRING
            && $tokens[$decName]['content'] !== $fileName
        ) {
            $error = '%s name doesn\'t match filename; expected "%s %s"';
            $data  = [
                ucfirst($tokens[$stackPtr]['content']),
                $tokens[$stackPtr]['content'],
                $fileName,
            ];
            $phpcsFile->addError($error, $stackPtr, 'NoMatch', $data);
        }

        // Only check the first class in a file, we don't care about helper
        // classes in tests for example.
        return ($phpcsFile->numTokens + 1);

    }//end process()

https://git.drupalcode.org/project/coder/-/blob/8.x-3.x/coder_sniffer/Dr...

Re #4, no, as I see.

Thank you @klausi!

jungle’s picture

Status: Needs review » Postponed (maintainer needs more info)
            $error = '%s name doesn\'t match filename; expected "%s %s"';

Looks like this is the one. checking further.

jungle’s picture

Status: Postponed (maintainer needs more info) » Closed (works as designed)

Yes, found it, it's Drupal.Classes.ClassFileName, Thank you @klausi!

jungle’s picture