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

PHPCSStandards / PHP_CodeSniffer / 15637524486

13 Jun 2025 02:54PM UTC coverage: 78.436% (+0.06%) from 78.375%
15637524486

Pull #1108

github

web-flow
Merge ce5067991 into ef0b6a62c
Pull Request #1108: Squiz/SelfMemberReference: update XML doc

25193 of 32119 relevant lines covered (78.44%)

69.39 hits per line

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

98.44
/src/Standards/Squiz/Sniffs/Commenting/BlockCommentSniff.php
1
<?php
2
/**
3
 * Verifies that block comments are used appropriately.
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 BlockCommentSniff implements Sniff
17
{
18

19
    /**
20
     * The --tab-width CLI value that is being used.
21
     *
22
     * @var integer
23
     */
24
    private $tabWidth = null;
25

26

27
    /**
28
     * Returns an array of tokens this test wants to listen for.
29
     *
30
     * @return array<int|string>
31
     */
32
    public function register()
3✔
33
    {
34
        return [
1✔
35
            T_COMMENT,
3✔
36
            T_DOC_COMMENT_OPEN_TAG,
3✔
37
        ];
2✔
38

39
    }//end register()
40

41

42
    /**
43
     * Processes this test, when one of its tokens is encountered.
44
     *
45
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being scanned.
46
     * @param int                         $stackPtr  The position of the current token in the
47
     *                                               stack passed in $tokens.
48
     *
49
     * @return void
50
     */
51
    public function process(File $phpcsFile, $stackPtr)
3✔
52
    {
53
        if ($this->tabWidth === null) {
3✔
54
            if (isset($phpcsFile->config->tabWidth) === false || $phpcsFile->config->tabWidth === 0) {
3✔
55
                // We have no idea how wide tabs are, so assume 4 spaces for fixing.
56
                $this->tabWidth = 4;
×
57
            } else {
58
                $this->tabWidth = $phpcsFile->config->tabWidth;
3✔
59
            }
60
        }
1✔
61

62
        $tokens = $phpcsFile->getTokens();
3✔
63

64
        // If it's an inline comment, return.
65
        if (substr($tokens[$stackPtr]['content'], 0, 2) !== '/*') {
3✔
66
            return;
3✔
67
        }
68

69
        // If this is a function/class/interface/enum/property/const doc block comment, skip it.
70
        // We are only interested in inline doc block comments.
71
        if ($tokens[$stackPtr]['code'] === T_DOC_COMMENT_OPEN_TAG) {
3✔
72
            $nextToken = $stackPtr;
3✔
73
            do {
74
                $nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, ($nextToken + 1), null, true);
3✔
75
                if ($tokens[$nextToken]['code'] === T_ATTRIBUTE) {
3✔
76
                    $nextToken = $tokens[$nextToken]['attribute_closer'];
3✔
77
                    continue;
3✔
78
                }
79

80
                break;
3✔
81
            } while (true);
3✔
82

83
            $ignore  = Tokens::$scopeModifiers;
3✔
84
            $ignore += [
1✔
85
                T_CLASS     => true,
3✔
86
                T_INTERFACE => true,
3✔
87
                T_TRAIT     => true,
3✔
88
                T_ENUM      => true,
3✔
89
                T_FUNCTION  => true,
3✔
90
                T_FINAL     => true,
3✔
91
                T_STATIC    => true,
3✔
92
                T_ABSTRACT  => true,
3✔
93
                T_CONST     => true,
3✔
94
                T_VAR       => true,
3✔
95
                T_READONLY  => true,
3✔
96
            ];
1✔
97
            if (isset($ignore[$tokens[$nextToken]['code']]) === true) {
3✔
98
                return;
3✔
99
            }
100

101
            $prevToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true);
3✔
102
            if ($tokens[$prevToken]['code'] === T_OPEN_TAG) {
3✔
103
                return;
×
104
            }
105

106
            $error = 'Block comments must be started with /*';
3✔
107
            $fix   = $phpcsFile->addFixableError($error, $stackPtr, 'WrongStart');
3✔
108
            if ($fix === true) {
3✔
109
                $phpcsFile->fixer->replaceToken($stackPtr, '/*');
3✔
110
            }
1✔
111

112
            $end = $tokens[$stackPtr]['comment_closer'];
3✔
113
            if ($tokens[$end]['content'] !== '*/') {
3✔
114
                $error = 'Block comments must be ended with */';
3✔
115
                $fix   = $phpcsFile->addFixableError($error, $end, 'WrongEnd');
3✔
116
                if ($fix === true) {
3✔
117
                    $phpcsFile->fixer->replaceToken($end, '*/');
3✔
118
                }
1✔
119
            }
1✔
120

121
            return;
3✔
122
        }//end if
123

124
        $commentLines  = [$stackPtr];
3✔
125
        $nextComment   = $stackPtr;
3✔
126
        $lastLine      = $tokens[$stackPtr]['line'];
3✔
127
        $commentString = $tokens[$stackPtr]['content'];
3✔
128

129
        // Construct the comment into an array.
130
        while (($nextComment = $phpcsFile->findNext(T_WHITESPACE, ($nextComment + 1), null, true)) !== false) {
3✔
131
            if ($tokens[$nextComment]['code'] !== $tokens[$stackPtr]['code']
3✔
132
                && isset(Tokens::$phpcsCommentTokens[$tokens[$nextComment]['code']]) === false
3✔
133
            ) {
1✔
134
                // Found the next bit of code.
135
                break;
3✔
136
            }
137

138
            if (($tokens[$nextComment]['line'] - 1) !== $lastLine) {
3✔
139
                // Not part of the block.
140
                break;
3✔
141
            }
142

143
            $lastLine       = $tokens[$nextComment]['line'];
3✔
144
            $commentLines[] = $nextComment;
3✔
145
            $commentString .= $tokens[$nextComment]['content'];
3✔
146
            if ($tokens[$nextComment]['code'] === T_DOC_COMMENT_CLOSE_TAG
3✔
147
                || substr($tokens[$nextComment]['content'], -2) === '*/'
3✔
148
            ) {
1✔
149
                break;
3✔
150
            }
151
        }//end while
1✔
152

153
        $commentText = str_replace($phpcsFile->eolChar, '', $commentString);
3✔
154
        $commentText = trim($commentText, "/* \t");
3✔
155
        if ($commentText === '') {
3✔
156
            $error = 'Empty block comment not allowed';
3✔
157
            $fix   = $phpcsFile->addFixableError($error, $stackPtr, 'Empty');
3✔
158
            if ($fix === true) {
3✔
159
                $phpcsFile->fixer->beginChangeset();
3✔
160
                $phpcsFile->fixer->replaceToken($stackPtr, '');
3✔
161
                $lastToken = array_pop($commentLines);
3✔
162
                for ($i = ($stackPtr + 1); $i <= $lastToken; $i++) {
3✔
163
                    $phpcsFile->fixer->replaceToken($i, '');
3✔
164
                }
1✔
165

166
                $phpcsFile->fixer->endChangeset();
3✔
167
            }
1✔
168

169
            return;
3✔
170
        }
171

172
        if (count($commentLines) === 1) {
3✔
173
            $error = 'Single line block comment not allowed; use inline ("// text") comment instead';
3✔
174

175
            // Only fix comments when they are the last token on a line.
176
            $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
3✔
177
            if ($tokens[$stackPtr]['line'] !== $tokens[$nextNonEmpty]['line']) {
3✔
178
                $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SingleLine');
3✔
179
                if ($fix === true) {
3✔
180
                    $comment = '// '.$commentText.$phpcsFile->eolChar;
3✔
181
                    $phpcsFile->fixer->replaceToken($stackPtr, $comment);
3✔
182
                }
1✔
183
            } else {
1✔
184
                $phpcsFile->addError($error, $stackPtr, 'SingleLine');
3✔
185
            }
186

187
            return;
3✔
188
        }
189

190
        $content = trim($tokens[$stackPtr]['content']);
3✔
191
        if ($content !== '/*' && $content !== '/**') {
3✔
192
            $error = 'Block comment text must start on a new line';
3✔
193
            $fix   = $phpcsFile->addFixableError($error, $stackPtr, 'NoNewLine');
3✔
194
            if ($fix === true) {
3✔
195
                $indent = '';
3✔
196
                if ($tokens[($stackPtr - 1)]['code'] === T_WHITESPACE) {
3✔
197
                    if (isset($tokens[($stackPtr - 1)]['orig_content']) === true) {
3✔
198
                        $indent = $tokens[($stackPtr - 1)]['orig_content'];
3✔
199
                    } else {
1✔
200
                        $indent = $tokens[($stackPtr - 1)]['content'];
3✔
201
                    }
202
                }
1✔
203

204
                $comment = preg_replace(
3✔
205
                    '/^(\s*\/\*\*?)/',
3✔
206
                    '$1'.$phpcsFile->eolChar.$indent,
3✔
207
                    $tokens[$stackPtr]['content'],
3✔
208
                    1
2✔
209
                );
2✔
210
                $phpcsFile->fixer->replaceToken($stackPtr, $comment);
3✔
211
            }
1✔
212

213
            return;
3✔
214
        }//end if
215

216
        $starColumn = $tokens[$stackPtr]['column'];
3✔
217
        $hasStars   = false;
3✔
218

219
        // Make sure first line isn't blank.
220
        if (trim($tokens[$commentLines[1]]['content']) === '') {
3✔
221
            $error = 'Empty line not allowed at start of comment';
3✔
222
            $fix   = $phpcsFile->addFixableError($error, $commentLines[1], 'HasEmptyLine');
3✔
223
            if ($fix === true) {
3✔
224
                $phpcsFile->fixer->replaceToken($commentLines[1], '');
3✔
225
            }
1✔
226
        } else {
1✔
227
            // Check indentation of first line.
228
            $content      = $tokens[$commentLines[1]]['content'];
3✔
229
            $commentText  = ltrim($content);
3✔
230
            $leadingSpace = (strlen($content) - strlen($commentText));
3✔
231

232
            $expected = ($starColumn + 3);
3✔
233
            if ($commentText[0] === '*') {
3✔
234
                $expected = $starColumn;
3✔
235
                $hasStars = true;
3✔
236
            }
1✔
237

238
            if ($leadingSpace !== $expected) {
3✔
239
                $expectedTxt = $expected.' space';
3✔
240
                if ($expected !== 1) {
3✔
241
                    $expectedTxt .= 's';
3✔
242
                }
1✔
243

244
                $data = [
1✔
245
                    $expectedTxt,
3✔
246
                    $leadingSpace,
3✔
247
                ];
2✔
248

249
                $error = 'First line of comment not aligned correctly; expected %s but found %s';
3✔
250
                $fix   = $phpcsFile->addFixableError($error, $commentLines[1], 'FirstLineIndent', $data);
3✔
251
                if ($fix === true) {
3✔
252
                    if (isset($tokens[$commentLines[1]]['orig_content']) === true
3✔
253
                        && $tokens[$commentLines[1]]['orig_content'][0] === "\t"
3✔
254
                    ) {
1✔
255
                        // Line is indented using tabs.
256
                        $padding  = str_repeat("\t", floor($expected / $this->tabWidth));
3✔
257
                        $padding .= str_repeat(' ', ($expected % $this->tabWidth));
3✔
258
                    } else {
1✔
259
                        $padding = str_repeat(' ', $expected);
3✔
260
                    }
261

262
                    $phpcsFile->fixer->replaceToken($commentLines[1], $padding.$commentText);
3✔
263
                }
1✔
264
            }//end if
1✔
265

266
            if (preg_match('/^\p{Ll}/u', $commentText) === 1) {
3✔
267
                $error = 'Block comments must start with a capital letter';
3✔
268
                $phpcsFile->addError($error, $commentLines[1], 'NoCapital');
3✔
269
            }
1✔
270
        }//end if
271

272
        // Check that each line of the comment is indented past the star.
273
        foreach ($commentLines as $line) {
3✔
274
            // First and last lines (comment opener and closer) are handled separately.
275
            if ($line === $commentLines[(count($commentLines) - 1)] || $line === $commentLines[0]) {
3✔
276
                continue;
3✔
277
            }
278

279
            // First comment line was handled above.
280
            if ($line === $commentLines[1]) {
3✔
281
                continue;
3✔
282
            }
283

284
            // If it's empty, continue.
285
            if (trim($tokens[$line]['content']) === '') {
3✔
286
                continue;
3✔
287
            }
288

289
            $commentText  = ltrim($tokens[$line]['content']);
3✔
290
            $leadingSpace = (strlen($tokens[$line]['content']) - strlen($commentText));
3✔
291

292
            $expected = ($starColumn + 3);
3✔
293
            if ($commentText[0] === '*') {
3✔
294
                $expected = $starColumn;
3✔
295
                $hasStars = true;
3✔
296
            }
1✔
297

298
            if ($leadingSpace < $expected) {
3✔
299
                $expectedTxt = $expected.' space';
3✔
300
                if ($expected !== 1) {
3✔
301
                    $expectedTxt .= 's';
3✔
302
                }
1✔
303

304
                $data = [
1✔
305
                    $expectedTxt,
3✔
306
                    $leadingSpace,
3✔
307
                ];
2✔
308

309
                $error = 'Comment line indented incorrectly; expected at least %s but found %s';
3✔
310
                $fix   = $phpcsFile->addFixableError($error, $line, 'LineIndent', $data);
3✔
311
                if ($fix === true) {
3✔
312
                    if (isset($tokens[$line]['orig_content']) === true
3✔
313
                        && $tokens[$line]['orig_content'][0] === "\t"
3✔
314
                    ) {
1✔
315
                        // Line is indented using tabs.
316
                        $padding  = str_repeat("\t", floor($expected / $this->tabWidth));
×
317
                        $padding .= str_repeat(' ', ($expected % $this->tabWidth));
×
318
                    } else {
319
                        $padding = str_repeat(' ', $expected);
3✔
320
                    }
321

322
                    $phpcsFile->fixer->replaceToken($line, $padding.$commentText);
3✔
323
                }
1✔
324
            }//end if
1✔
325
        }//end foreach
1✔
326

327
        // Finally, test the last line is correct.
328
        $lastIndex   = (count($commentLines) - 1);
3✔
329
        $content     = $tokens[$commentLines[$lastIndex]]['content'];
3✔
330
        $commentText = ltrim($content);
3✔
331
        if ($commentText !== '*/' && $commentText !== '**/') {
3✔
332
            $error = 'Comment closer must be on a new line';
3✔
333
            $phpcsFile->addError($error, $commentLines[$lastIndex], 'CloserSameLine');
3✔
334
        } else {
1✔
335
            $leadingSpace = (strlen($content) - strlen($commentText));
3✔
336

337
            $expected = ($starColumn - 1);
3✔
338
            if ($hasStars === true) {
3✔
339
                $expected = $starColumn;
3✔
340
            }
1✔
341

342
            if ($leadingSpace !== $expected) {
3✔
343
                $expectedTxt = $expected.' space';
3✔
344
                if ($expected !== 1) {
3✔
345
                    $expectedTxt .= 's';
3✔
346
                }
1✔
347

348
                $data = [
1✔
349
                    $expectedTxt,
3✔
350
                    $leadingSpace,
3✔
351
                ];
2✔
352

353
                $error = 'Last line of comment aligned incorrectly; expected %s but found %s';
3✔
354
                $fix   = $phpcsFile->addFixableError($error, $commentLines[$lastIndex], 'LastLineIndent', $data);
3✔
355
                if ($fix === true) {
3✔
356
                    if (isset($tokens[$line]['orig_content']) === true
3✔
357
                        && $tokens[$line]['orig_content'][0] === "\t"
3✔
358
                    ) {
1✔
359
                        // Line is indented using tabs.
360
                        $padding  = str_repeat("\t", floor($expected / $this->tabWidth));
3✔
361
                        $padding .= str_repeat(' ', ($expected % $this->tabWidth));
3✔
362
                    } else {
1✔
363
                        $padding = str_repeat(' ', $expected);
3✔
364
                    }
365

366
                    $phpcsFile->fixer->replaceToken($commentLines[$lastIndex], $padding.$commentText);
3✔
367
                }
1✔
368
            }//end if
1✔
369
        }//end if
370

371
        // Check that the lines before and after this comment are blank.
372
        $contentBefore = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
3✔
373
        if ((isset($tokens[$contentBefore]['scope_closer']) === true
3✔
374
            && $tokens[$contentBefore]['scope_opener'] === $contentBefore)
3✔
375
            || $tokens[$contentBefore]['code'] === T_OPEN_TAG
3✔
376
            || $tokens[$contentBefore]['code'] === T_OPEN_TAG_WITH_ECHO
3✔
377
        ) {
1✔
378
            if (($tokens[$stackPtr]['line'] - $tokens[$contentBefore]['line']) !== 1) {
3✔
379
                $error = 'Empty line not required before block comment';
3✔
380
                $phpcsFile->addError($error, $stackPtr, 'HasEmptyLineBefore');
3✔
381
            }
1✔
382
        } else {
1✔
383
            if (($tokens[$stackPtr]['line'] - $tokens[$contentBefore]['line']) < 2) {
3✔
384
                $error = 'Empty line required before block comment';
3✔
385
                $phpcsFile->addError($error, $stackPtr, 'NoEmptyLineBefore');
3✔
386
            }
1✔
387
        }
388

389
        $commentCloser = $commentLines[$lastIndex];
3✔
390
        $contentAfter  = $phpcsFile->findNext(T_WHITESPACE, ($commentCloser + 1), null, true);
3✔
391
        if ($contentAfter !== false && ($tokens[$contentAfter]['line'] - $tokens[$commentCloser]['line']) < 2) {
3✔
392
            $error = 'Empty line required after block comment';
3✔
393
            $phpcsFile->addError($error, $commentCloser, 'NoEmptyLineAfter');
3✔
394
        }
1✔
395

396
    }//end process()
2✔
397

398

399
}//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

© 2026 Coveralls, Inc