View source
<?php
namespace Drupal\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;
class ClassCommentSniff implements Sniff {
public function register() {
return array(
T_CLASS,
T_INTERFACE,
T_TRAIT,
);
}
public function process(File $phpcsFile, $stackPtr) {
$tokens = $phpcsFile
->getTokens();
$find = Tokens::$methodPrefixes;
$find[] = T_WHITESPACE;
$name = $tokens[$stackPtr]['content'];
$commentEnd = $phpcsFile
->findPrevious($find, $stackPtr - 1, null, true);
if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG && $tokens[$commentEnd]['code'] !== T_COMMENT) {
$fix = $phpcsFile
->addFixableError('Missing %s doc comment', $stackPtr, 'Missing', array(
$name,
));
if ($fix === true) {
$phpcsFile->fixer
->addContent($commentEnd, "\n/**\n *\n */");
}
return;
}
if ($tokens[$commentEnd]['code'] === T_DOC_COMMENT_CLOSE_TAG) {
$start = $tokens[$commentEnd]['comment_opener'] - 1;
}
else {
$start = $commentEnd - 1;
}
$fileTag = $phpcsFile
->findNext(T_DOC_COMMENT_TAG, $start + 1, $commentEnd, false, '@file');
if ($fileTag !== false) {
$fix = $phpcsFile
->addFixableError('Missing %s doc comment', $stackPtr, 'Missing', array(
$name,
));
if ($fix === true) {
$phpcsFile->fixer
->addContent($commentEnd, "\n/**\n *\n */");
}
return;
}
if ($tokens[$commentEnd]['code'] === T_COMMENT) {
$fix = $phpcsFile
->addFixableError('You must use "/**" style comments for a %s comment', $stackPtr, 'WrongStyle', array(
$name,
));
if ($fix === true) {
$phpcsFile->fixer
->beginChangeset();
$comment = '';
for ($i = $commentEnd; $tokens[$i]['code'] === T_COMMENT; $i--) {
$comment = ' *' . ltrim($tokens[$i]['content'], '/* ') . $comment;
$phpcsFile->fixer
->replaceToken($i, '');
}
$phpcsFile->fixer
->replaceToken($commentEnd, "/**\n" . rtrim($comment, "*/\n") . "\n */");
$phpcsFile->fixer
->endChangeset();
}
return;
}
if ($tokens[$commentEnd]['line'] !== $tokens[$stackPtr]['line'] - 1) {
$error = 'There must be exactly one newline after the %s comment';
$fix = $phpcsFile
->addFixableError($error, $commentEnd, 'SpacingAfter', array(
$name,
));
if ($fix === true) {
$phpcsFile->fixer
->beginChangeset();
for ($i = $commentEnd + 1; $tokens[$i]['code'] === T_WHITESPACE && $i < $stackPtr; $i++) {
$phpcsFile->fixer
->replaceToken($i, '');
}
$phpcsFile->fixer
->addContent($commentEnd, "\n");
$phpcsFile->fixer
->endChangeset();
}
}
}
}