public function ClassNameSniff::process in Coder 8.3
Same name and namespace in other branches
- 8.2 coder_sniffer/DrupalPractice/Sniffs/General/ClassNameSniff.php \DrupalPractice\Sniffs\General\ClassNameSniff::process()
- 8.3.x coder_sniffer/DrupalPractice/Sniffs/General/ClassNameSniff.php \DrupalPractice\Sniffs\General\ClassNameSniff::process()
Processes this test, when one of its tokens is encountered.
Parameters
\PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.:
int $stackPtr The position of the function: name in the stack.
Return value
void
File
- coder_sniffer/
DrupalPractice/ Sniffs/ General/ ClassNameSniff.php, line 52
Class
- ClassNameSniff
- Checks that classes without namespaces are properly prefixed with the module name.
Namespace
DrupalPractice\Sniffs\GeneralCode
public function process(File $phpcsFile, $stackPtr) {
// If there is a PHP 5.3 namespace declaration in the file we return
// immediately as classes can be named arbitrary within a namespace.
$namespace = $phpcsFile
->findPrevious(T_NAMESPACE, $stackPtr - 1);
if ($namespace !== false) {
return;
}
$moduleName = Project::getName($phpcsFile);
if ($moduleName === false) {
return;
}
$tokens = $phpcsFile
->getTokens();
$className = $phpcsFile
->findNext(T_STRING, $stackPtr);
$name = trim($tokens[$className]['content']);
// Underscores are omitted in class names. Also convert all characters
// to lower case to compare them later.
$classPrefix = strtolower(str_replace('_', '', $moduleName));
// Views classes might have underscores in the name, which is also fine.
$viewsPrefix = strtolower($moduleName);
$name = strtolower($name);
if (strpos($name, $classPrefix) !== 0 && strpos($name, $viewsPrefix) !== 0) {
$warning = '%s name must be prefixed with the project name "%s"';
$nameParts = explode('_', $moduleName);
$camelName = '';
foreach ($nameParts as &$part) {
$camelName .= ucfirst($part);
}
$errorData = [
ucfirst($tokens[$stackPtr]['content']),
$camelName,
];
$phpcsFile
->addWarning($warning, $className, 'ClassPrefix', $errorData);
}
}