8 use PHP_CodeSniffer\Sniffs\Sniff;
9 use PHP_CodeSniffer\Files\File;
33 self::FIRST_LEVEL_COMMENT => T_STRING,
34 self::SECOND_LEVEL_COMMENT => T_DEC,
47 public function register()
55 public function process(File $phpcsFile, $stackPtr)
57 $tokens = $phpcsFile->getTokens();
59 if ((T_STRING !==
$tokens[$stackPtr][
'code'])
60 || (self::COMMENT_STRING !==
$tokens[$stackPtr][
'content'])
61 || (1 ===
$tokens[$stackPtr][
'line'])
66 $textInSameLine = $phpcsFile->findPrevious([T_STRING, T_STYLE], $stackPtr - 1);
69 if ((
false !== $textInSameLine)
70 && (
$tokens[$textInSameLine][
'line'] ===
$tokens[$stackPtr][
'line'])
72 $this->validateInlineComment($phpcsFile, $stackPtr,
$tokens);
77 if (!in_array(
$tokens[$stackPtr + 1][
'content'], [
82 $phpcsFile->addError(
'Level\'s comment does not have 2 spaces after "//"', $stackPtr,
'SpacesMissed');
85 if (!$this->isNthLevelComment($phpcsFile, $stackPtr,
$tokens)) {
89 if (!$this->checkNthLevelComment($phpcsFile, $stackPtr,
$tokens)) {
91 'First and second level comments must be surrounded by empty lines',
106 private function validateInlineComment(File $phpcsFile, $stackPtr, array
$tokens)
109 $phpcsFile->addError(
'Inline comment should have 1 space after "//"', $stackPtr,
'SpaceMissedAfter');
112 $phpcsFile->addError(
'Inline comment should have 1 space before "//"', $stackPtr,
'SpaceMissedBefore');
124 private function isNthLevelComment(File $phpcsFile, $stackPtr, array
$tokens)
126 $nthLevelCommentFound =
false;
129 foreach ($this->levelComments as
$code => $comment) {
130 $levelComment = $phpcsFile->findNext($comment, $stackPtr,
null,
false,
$code);
131 if (
false !== $levelComment) {
132 $nthLevelCommentFound =
true;
137 if (
false === $nthLevelCommentFound) {
141 $currentLine =
$tokens[$stackPtr][
'line'];
142 $levelCommentLine =
$tokens[$levelComment][
'line'];
144 if ($currentLine !== $levelCommentLine) {
159 private function checkNthLevelComment(File $phpcsFile, $stackPtr, array
$tokens)
163 $nextLine = $phpcsFile->findNext(
171 if (
false === $nextLine) {
181 $commentLinePtr = $stackPtr;
182 while (
$tokens[$commentLinePtr - 2][
'line'] > 1) {
183 $commentLinePtr = $phpcsFile->findPrevious(T_STRING, $commentLinePtr - 1,
null,
false,
'//');
185 if (
false === $commentLinePtr) {