• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPCSStandards / PHP_CodeSniffer / 15253296250

26 May 2025 11:55AM UTC coverage: 78.632% (+0.3%) from 78.375%
15253296250

Pull #1105

github

web-flow
Merge d9441d98f into caf806050
Pull Request #1105: Skip tests when 'git' command is not available

19665 of 25009 relevant lines covered (78.63%)

88.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.82
/src/Standards/Squiz/Sniffs/Commenting/InlineCommentSniff.php
1
<?php
2
/**
3
 * Checks that there is adequate spacing between comments.
4
 *
5
 * @author    Greg Sherwood <gsherwood@squiz.net>
6
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
7
 * @license   https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
8
 */
9

10
namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting;
11

12
use PHP_CodeSniffer\Files\File;
13
use PHP_CodeSniffer\Sniffs\Sniff;
14
use PHP_CodeSniffer\Util\Tokens;
15

16
class InlineCommentSniff implements Sniff
17
{
18

19

20
    /**
21
     * Returns an array of tokens this test wants to listen for.
22
     *
23
     * @return array<int|string>
24
     */
25
    public function register()
3✔
26
    {
27
        return [
2✔
28
            T_COMMENT,
3✔
29
            T_DOC_COMMENT_OPEN_TAG,
3✔
30
        ];
2✔
31

32
    }//end register()
33

34

35
    /**
36
     * Processes this test, when one of its tokens is encountered.
37
     *
38
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
39
     * @param int                         $stackPtr  The position of the current token in the
40
     *                                               stack passed in $tokens.
41
     *
42
     * @return void|int
43
     */
44
    public function process(File $phpcsFile, $stackPtr)
3✔
45
    {
46
        $tokens = $phpcsFile->getTokens();
3✔
47

48
        // If this is a function/class/interface doc block comment, skip it.
49
        // We are only interested in inline doc block comments, which are
50
        // not allowed.
51
        if ($tokens[$stackPtr]['code'] === T_DOC_COMMENT_OPEN_TAG) {
3✔
52
            $nextToken = $stackPtr;
3✔
53
            do {
54
                $nextToken = $phpcsFile->findNext(Tokens::EMPTY_TOKENS, ($nextToken + 1), null, true);
3✔
55
                if ($tokens[$nextToken]['code'] === T_ATTRIBUTE) {
3✔
56
                    $nextToken = $tokens[$nextToken]['attribute_closer'];
3✔
57
                    continue;
3✔
58
                }
59

60
                break;
3✔
61
            } while (true);
3✔
62

63
            $ignore = [
2✔
64
                T_CLASS,
3✔
65
                T_INTERFACE,
3✔
66
                T_TRAIT,
3✔
67
                T_ENUM,
3✔
68
                T_FUNCTION,
3✔
69
                T_CLOSURE,
3✔
70
                T_PUBLIC,
3✔
71
                T_PRIVATE,
3✔
72
                T_PROTECTED,
3✔
73
                T_FINAL,
3✔
74
                T_STATIC,
3✔
75
                T_ABSTRACT,
3✔
76
                T_READONLY,
3✔
77
                T_CONST,
3✔
78
                T_INCLUDE,
3✔
79
                T_INCLUDE_ONCE,
3✔
80
                T_REQUIRE,
3✔
81
                T_REQUIRE_ONCE,
3✔
82
            ];
2✔
83

84
            if (in_array($tokens[$nextToken]['code'], $ignore, true) === true) {
3✔
85
                return;
3✔
86
            }
87

88
            $prevToken = $phpcsFile->findPrevious(
3✔
89
                Tokens::EMPTY_TOKENS,
3✔
90
                ($stackPtr - 1),
3✔
91
                null,
3✔
92
                true
3✔
93
            );
2✔
94

95
            if ($tokens[$prevToken]['code'] === T_OPEN_TAG) {
3✔
96
                return;
×
97
            }
98

99
            if ($tokens[$stackPtr]['content'] === '/**') {
3✔
100
                $error = 'Inline doc block comments are not allowed; use "/* Comment */" or "// Comment" instead';
3✔
101
                $phpcsFile->addError($error, $stackPtr, 'DocBlock');
3✔
102
            }
103
        }//end if
104

105
        if ($tokens[$stackPtr]['content'][0] === '#') {
3✔
106
            $error = 'Perl-style comments are not allowed; use "// Comment" instead';
3✔
107
            $fix   = $phpcsFile->addFixableError($error, $stackPtr, 'WrongStyle');
3✔
108
            if ($fix === true) {
3✔
109
                $comment = ltrim($tokens[$stackPtr]['content'], "# \t");
3✔
110
                $phpcsFile->fixer->replaceToken($stackPtr, "// $comment");
3✔
111
            }
112
        }
113

114
        // We don't want end of block comments. Check if the last token before the
115
        // comment is a closing curly brace.
116
        $previousContent = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
3✔
117
        if ($tokens[$previousContent]['line'] === $tokens[$stackPtr]['line']) {
3✔
118
            if ($tokens[$previousContent]['code'] === T_CLOSE_CURLY_BRACKET) {
3✔
119
                return;
3✔
120
            }
121
        }
122

123
        // Only want inline comments.
124
        if (substr($tokens[$stackPtr]['content'], 0, 2) !== '//') {
3✔
125
            return;
3✔
126
        }
127

128
        $commentTokens = [$stackPtr];
3✔
129

130
        $nextComment = $stackPtr;
3✔
131
        $lastComment = $stackPtr;
3✔
132
        while (($nextComment = $phpcsFile->findNext(T_COMMENT, ($nextComment + 1), null, false)) !== false) {
3✔
133
            if ($tokens[$nextComment]['line'] !== ($tokens[$lastComment]['line'] + 1)) {
3✔
134
                break;
3✔
135
            }
136

137
            // Only want inline comments.
138
            if (substr($tokens[$nextComment]['content'], 0, 2) !== '//') {
3✔
139
                break;
3✔
140
            }
141

142
            // There is a comment on the very next line. If there is
143
            // no code between the comments, they are part of the same
144
            // comment block.
145
            $prevNonWhitespace = $phpcsFile->findPrevious(T_WHITESPACE, ($nextComment - 1), $lastComment, true);
3✔
146
            if ($prevNonWhitespace !== $lastComment) {
3✔
147
                break;
3✔
148
            }
149

150
            $commentTokens[] = $nextComment;
3✔
151
            $lastComment     = $nextComment;
3✔
152
        }//end while
153

154
        $commentText = '';
3✔
155
        foreach ($commentTokens as $lastCommentToken) {
3✔
156
            $comment = rtrim($tokens[$lastCommentToken]['content']);
3✔
157

158
            if (trim(substr($comment, 2)) === '') {
3✔
159
                continue;
3✔
160
            }
161

162
            $spaceCount = 0;
3✔
163
            $tabFound   = false;
3✔
164

165
            $commentLength = strlen($comment);
3✔
166
            for ($i = 2; $i < $commentLength; $i++) {
3✔
167
                if ($comment[$i] === "\t") {
3✔
168
                    $tabFound = true;
3✔
169
                    break;
3✔
170
                }
171

172
                if ($comment[$i] !== ' ') {
3✔
173
                    break;
3✔
174
                }
175

176
                $spaceCount++;
3✔
177
            }
178

179
            $fix = false;
3✔
180
            if ($tabFound === true) {
3✔
181
                $error = 'Tab found before comment text; expected "// %s" but found "%s"';
3✔
182
                $data  = [
2✔
183
                    ltrim(substr($comment, 2)),
3✔
184
                    $comment,
3✔
185
                ];
2✔
186
                $fix   = $phpcsFile->addFixableError($error, $lastCommentToken, 'TabBefore', $data);
3✔
187
            } else if ($spaceCount === 0) {
3✔
188
                $error = 'No space found before comment text; expected "// %s" but found "%s"';
3✔
189
                $data  = [
2✔
190
                    substr($comment, 2),
3✔
191
                    $comment,
3✔
192
                ];
2✔
193
                $fix   = $phpcsFile->addFixableError($error, $lastCommentToken, 'NoSpaceBefore', $data);
3✔
194
            } else if ($spaceCount > 1) {
3✔
195
                $error = 'Expected 1 space before comment text but found %s; use block comment if you need indentation';
3✔
196
                $data  = [
2✔
197
                    $spaceCount,
3✔
198
                    substr($comment, (2 + $spaceCount)),
3✔
199
                    $comment,
3✔
200
                ];
2✔
201
                $fix   = $phpcsFile->addFixableError($error, $lastCommentToken, 'SpacingBefore', $data);
3✔
202
            }//end if
203

204
            if ($fix === true) {
3✔
205
                $newComment = '// '.ltrim($tokens[$lastCommentToken]['content'], "/\t ");
3✔
206
                $phpcsFile->fixer->replaceToken($lastCommentToken, $newComment);
3✔
207
            }
208

209
            $commentText .= trim(substr($tokens[$lastCommentToken]['content'], 2));
3✔
210
        }//end foreach
211

212
        if ($commentText === '') {
3✔
213
            $error = 'Blank comments are not allowed';
3✔
214
            $fix   = $phpcsFile->addFixableError($error, $stackPtr, 'Empty');
3✔
215
            if ($fix === true) {
3✔
216
                $phpcsFile->fixer->replaceToken($stackPtr, '');
3✔
217
            }
218

219
            return ($lastCommentToken + 1);
3✔
220
        }
221

222
        if (preg_match('/^\p{Ll}/u', $commentText) === 1) {
3✔
223
            $error = 'Inline comments must start with a capital letter';
3✔
224
            $phpcsFile->addError($error, $stackPtr, 'NotCapital');
3✔
225
        }
226

227
        // Only check the end of comment character if the start of the comment
228
        // is a letter, indicating that the comment is just standard text.
229
        if (preg_match('/^\p{L}/u', $commentText) === 1) {
3✔
230
            $commentCloser   = $commentText[(strlen($commentText) - 1)];
3✔
231
            $acceptedClosers = [
2✔
232
                'full-stops'        => '.',
3✔
233
                'exclamation marks' => '!',
2✔
234
                'or question marks' => '?',
2✔
235
            ];
2✔
236

237
            if (in_array($commentCloser, $acceptedClosers, true) === false) {
3✔
238
                $error = 'Inline comments must end in %s';
3✔
239
                $ender = '';
3✔
240
                foreach ($acceptedClosers as $closerName => $symbol) {
3✔
241
                    $ender .= ' '.$closerName.',';
3✔
242
                }
243

244
                $ender = trim($ender, ' ,');
3✔
245
                $data  = [$ender];
3✔
246
                $phpcsFile->addError($error, $lastCommentToken, 'InvalidEndChar', $data);
3✔
247
            }
248
        }
249

250
        // Finally, the line below the last comment cannot be empty if this inline
251
        // comment is on a line by itself.
252
        if ($tokens[$previousContent]['line'] < $tokens[$stackPtr]['line']) {
3✔
253
            $next = $phpcsFile->findNext(T_WHITESPACE, ($lastCommentToken + 1), null, true);
3✔
254
            if ($next === false) {
3✔
255
                // Ignore if the comment is the last non-whitespace token in a file.
256
                return ($lastCommentToken + 1);
3✔
257
            }
258

259
            if ($tokens[$next]['code'] === T_DOC_COMMENT_OPEN_TAG) {
3✔
260
                // If this inline comment is followed by a docblock,
261
                // ignore spacing as docblock/function etc spacing rules
262
                // are likely to conflict with our rules.
263
                return ($lastCommentToken + 1);
3✔
264
            }
265

266
            $errorCode = 'SpacingAfter';
3✔
267

268
            if (isset($tokens[$stackPtr]['conditions']) === true) {
3✔
269
                $conditions   = $tokens[$stackPtr]['conditions'];
3✔
270
                $type         = end($conditions);
3✔
271
                $conditionPtr = key($conditions);
3✔
272

273
                if (($type === T_FUNCTION || $type === T_CLOSURE)
3✔
274
                    && $tokens[$conditionPtr]['scope_closer'] === $next
3✔
275
                ) {
276
                    $errorCode = 'SpacingAfterAtFunctionEnd';
3✔
277
                }
278
            }
279

280
            for ($i = ($lastCommentToken + 1); $i < $phpcsFile->numTokens; $i++) {
3✔
281
                if ($tokens[$i]['line'] === ($tokens[$lastCommentToken]['line'] + 1)) {
3✔
282
                    if ($tokens[$i]['code'] !== T_WHITESPACE) {
3✔
283
                        return ($lastCommentToken + 1);
3✔
284
                    }
285
                } else if ($tokens[$i]['line'] > ($tokens[$lastCommentToken]['line'] + 1)) {
3✔
286
                    break;
3✔
287
                }
288
            }
289

290
            $error = 'There must be no blank line following an inline comment';
3✔
291
            $fix   = $phpcsFile->addFixableError($error, $lastCommentToken, $errorCode);
3✔
292
            if ($fix === true) {
3✔
293
                $phpcsFile->fixer->beginChangeset();
3✔
294
                for ($i = ($lastCommentToken + 1); $i < $next; $i++) {
3✔
295
                    if ($tokens[$i]['line'] === $tokens[$next]['line']) {
3✔
296
                        break;
×
297
                    }
298

299
                    $phpcsFile->fixer->replaceToken($i, '');
3✔
300
                }
301

302
                $phpcsFile->fixer->endChangeset();
3✔
303
            }
304
        }//end if
305

306
        return ($lastCommentToken + 1);
3✔
307

308
    }//end process()
309

310

311
}//end class
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc