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

PHPCSStandards / PHP_CodeSniffer / 14037418134

24 Mar 2025 02:08PM UTC coverage: 78.74% (+0.03%) from 78.708%
14037418134

Pull #880

github

web-flow
Merge d8bc30b92 into 79238b132
Pull Request #880: Generic/InlineControlStructure: bail early for control structures without body

50 of 50 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

24840 of 31547 relevant lines covered (78.74%)

66.44 hits per line

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

97.33
/src/Standards/Generic/Sniffs/ControlStructures/InlineControlStructureSniff.php
1
<?php
2
/**
3
 * Verifies that inline control statements are not present.
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\Generic\Sniffs\ControlStructures;
11

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

16
class InlineControlStructureSniff implements Sniff
17
{
18

19
    /**
20
     * A list of tokenizers this sniff supports.
21
     *
22
     * @var array
23
     */
24
    public $supportedTokenizers = [
25
        'PHP',
26
        'JS',
27
    ];
28

29
    /**
30
     * If true, an error will be thrown; otherwise a warning.
31
     *
32
     * @var boolean
33
     */
34
    public $error = true;
35

36

37
    /**
38
     * Returns an array of tokens this test wants to listen for.
39
     *
40
     * @return array<int|string>
41
     */
42
    public function register()
3✔
43
    {
44
        return [
1✔
45
            T_IF,
3✔
46
            T_ELSE,
3✔
47
            T_ELSEIF,
3✔
48
            T_FOREACH,
3✔
49
            T_WHILE,
3✔
50
            T_DO,
3✔
51
            T_FOR,
3✔
52
        ];
2✔
53

54
    }//end register()
55

56

57
    /**
58
     * Processes this test, when one of its tokens is encountered.
59
     *
60
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
61
     * @param int                         $stackPtr  The position of the current token in the
62
     *                                               stack passed in $tokens.
63
     *
64
     * @return void|int
65
     */
66
    public function process(File $phpcsFile, $stackPtr)
3✔
67
    {
68
        $tokens = $phpcsFile->getTokens();
3✔
69

70
        if (isset($tokens[$stackPtr]['scope_opener']) === true) {
3✔
71
            $phpcsFile->recordMetric($stackPtr, 'Control structure defined inline', 'no');
3✔
72
            return;
3✔
73
        }
74

75
        // Ignore the ELSE in ELSE IF. We'll process the IF part later.
76
        if ($tokens[$stackPtr]['code'] === T_ELSE) {
3✔
77
            $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
3✔
78
            if ($tokens[$next]['code'] === T_IF) {
3✔
79
                return;
3✔
80
            }
81
        }
1✔
82

83
        if (isset($tokens[$stackPtr]['parenthesis_closer']) === true) {
3✔
84
            $nextTokenIndex = ($tokens[$stackPtr]['parenthesis_closer'] + 1);
3✔
85
        } else if (in_array($tokens[$stackPtr]['code'], [T_ELSE, T_DO], true) === true) {
3✔
86
            $nextTokenIndex = ($stackPtr + 1);
3✔
87
        }
1✔
88

89
        if (isset($nextTokenIndex) === true) {
3✔
90
            $firstNonEmptyToken = $phpcsFile->findNext(Tokens::$emptyTokens, $nextTokenIndex, null, true);
3✔
91
            if ($firstNonEmptyToken === false) {
3✔
92
                // Live coding.
93
                return;
3✔
94
            }
95

96
            if ($tokens[$firstNonEmptyToken]['code'] === T_SEMICOLON) {
3✔
97
                // This is a control structure without a body. Bow out.
98
                $phpcsFile->recordMetric($stackPtr, 'Control structure defined inline', 'no');
3✔
99
                return;
3✔
100
            }
101
        }
1✔
102

103
        if (isset($tokens[$stackPtr]['parenthesis_opener'], $tokens[$stackPtr]['parenthesis_closer']) === false
3✔
104
            && $tokens[$stackPtr]['code'] !== T_ELSE
3✔
105
        ) {
1✔
106
            if ($tokens[$stackPtr]['code'] !== T_DO) {
3✔
107
                // Live coding or parse error.
108
                return;
3✔
109
            }
110

111
            $nextWhile = $phpcsFile->findNext(T_WHILE, ($stackPtr + 1));
3✔
112
            if ($nextWhile !== false
2✔
113
                && isset($tokens[$nextWhile]['parenthesis_opener'], $tokens[$nextWhile]['parenthesis_closer']) === false
3✔
114
            ) {
1✔
115
                // Live coding or parse error.
116
                return;
3✔
117
            }
118

119
            unset($nextWhile);
3✔
120
        }
1✔
121

122
        $start = $stackPtr;
3✔
123
        if (isset($tokens[$stackPtr]['parenthesis_closer']) === true) {
3✔
124
            $start = $tokens[$stackPtr]['parenthesis_closer'];
3✔
125
        }
1✔
126

127
        $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($start + 1), null, true);
3✔
128
        if ($nextNonEmpty === false) {
3✔
129
            // Live coding or parse error.
UNCOV
130
            return;
×
131
        }
132

133
        if ($tokens[$nextNonEmpty]['code'] === T_OPEN_CURLY_BRACKET
3✔
134
            || $tokens[$nextNonEmpty]['code'] === T_COLON
3✔
135
        ) {
1✔
136
            // T_CLOSE_CURLY_BRACKET missing, or alternative control structure with
137
            // T_END... missing. Either live coding, parse error or end
138
            // tag in short open tags and scan run with short_open_tag=Off.
139
            // Bow out completely as any further detection will be unreliable
140
            // and create incorrect fixes or cause fixer conflicts.
141
            return $phpcsFile->numTokens;
2✔
142
        }
143

144
        unset($nextNonEmpty, $start);
3✔
145

146
        // This is a control structure without an opening brace,
147
        // so it is an inline statement.
148
        if ($this->error === true) {
3✔
149
            $fix = $phpcsFile->addFixableError('Inline control structures are not allowed', $stackPtr, 'NotAllowed');
3✔
150
        } else {
1✔
151
            $fix = $phpcsFile->addFixableWarning('Inline control structures are discouraged', $stackPtr, 'Discouraged');
×
152
        }
153

154
        $phpcsFile->recordMetric($stackPtr, 'Control structure defined inline', 'yes');
3✔
155

156
        // Stop here if we are not fixing the error.
157
        if ($fix !== true) {
3✔
158
            return;
3✔
159
        }
160

161
        $phpcsFile->fixer->beginChangeset();
3✔
162
        if (isset($tokens[$stackPtr]['parenthesis_closer']) === true) {
3✔
163
            $closer = $tokens[$stackPtr]['parenthesis_closer'];
3✔
164
        } else {
1✔
165
            $closer = $stackPtr;
3✔
166
        }
167

168
        if ($tokens[($closer + 1)]['code'] === T_WHITESPACE) {
3✔
169
            $phpcsFile->fixer->addContent($closer, ' {');
3✔
170
        } else {
1✔
171
            $phpcsFile->fixer->addContent($closer, ' { ');
×
172
        }
173

174
        $fixableScopeOpeners = $this->register();
3✔
175

176
        $lastNonEmpty = $closer;
3✔
177
        for ($end = ($closer + 1); $end < $phpcsFile->numTokens; $end++) {
3✔
178
            if ($tokens[$end]['code'] === T_SEMICOLON) {
3✔
179
                break;
3✔
180
            }
181

182
            if ($tokens[$end]['code'] === T_CLOSE_TAG) {
3✔
183
                $end = $lastNonEmpty;
3✔
184
                break;
3✔
185
            }
186

187
            if (in_array($tokens[$end]['code'], $fixableScopeOpeners, true) === true
3✔
188
                && isset($tokens[$end]['scope_opener']) === false
3✔
189
            ) {
1✔
190
                // The best way to fix nested inline scopes is middle-out.
191
                // So skip this one. It will be detected and fixed on a future loop.
192
                $phpcsFile->fixer->rollbackChangeset();
3✔
193
                return;
3✔
194
            }
195

196
            if (isset($tokens[$end]['scope_opener']) === true) {
3✔
197
                $type = $tokens[$end]['code'];
3✔
198
                $end  = $tokens[$end]['scope_closer'];
3✔
199
                if ($type === T_DO
2✔
200
                    || $type === T_IF || $type === T_ELSEIF
3✔
201
                    || $type === T_TRY || $type === T_CATCH || $type === T_FINALLY
3✔
202
                ) {
1✔
203
                    $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), null, true);
3✔
204
                    if ($next === false) {
3✔
205
                        break;
×
206
                    }
207

208
                    $nextType = $tokens[$next]['code'];
3✔
209

210
                    // Let additional conditions loop and find their ending.
211
                    if (($type === T_IF
2✔
212
                        || $type === T_ELSEIF)
3✔
213
                        && ($nextType === T_ELSEIF
3✔
214
                        || $nextType === T_ELSE)
3✔
215
                    ) {
1✔
216
                        continue;
3✔
217
                    }
218

219
                    // Account for TRY... CATCH/FINALLY statements.
220
                    if (($type === T_TRY
2✔
221
                        || $type === T_CATCH
3✔
222
                        || $type === T_FINALLY)
3✔
223
                        && ($nextType === T_CATCH
3✔
224
                        || $nextType === T_FINALLY)
3✔
225
                    ) {
1✔
226
                        continue;
3✔
227
                    }
228

229
                    // Account for DO... WHILE conditions.
230
                    if ($type === T_DO && $nextType === T_WHILE) {
3✔
231
                        $end = $phpcsFile->findNext(T_SEMICOLON, ($next + 1));
3✔
232
                    }
1✔
233
                } else if ($type === T_CLOSURE) {
3✔
234
                    // There should be a semicolon after the closing brace.
235
                    $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), null, true);
3✔
236
                    if ($next !== false && $tokens[$next]['code'] === T_SEMICOLON) {
3✔
237
                        $end = $next;
3✔
238
                    }
1✔
239
                }//end if
1✔
240

241
                if ($tokens[$end]['code'] !== T_END_HEREDOC
3✔
242
                    && $tokens[$end]['code'] !== T_END_NOWDOC
3✔
243
                ) {
1✔
244
                    break;
3✔
245
                }
246
            }//end if
1✔
247

248
            if (isset($tokens[$end]['parenthesis_closer']) === true) {
3✔
249
                $end          = $tokens[$end]['parenthesis_closer'];
3✔
250
                $lastNonEmpty = $end;
3✔
251
                continue;
3✔
252
            }
253

254
            if ($tokens[$end]['code'] !== T_WHITESPACE) {
3✔
255
                $lastNonEmpty = $end;
3✔
256
            }
1✔
257
        }//end for
1✔
258

259
        if ($end === $phpcsFile->numTokens) {
3✔
260
            $end = $lastNonEmpty;
×
261
        }
262

263
        $nextContent = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), null, true);
3✔
264

265
        if ($nextContent === false || $tokens[$nextContent]['line'] !== $tokens[$end]['line']) {
3✔
266
            // Account for a comment on the end of the line.
267
            for ($endLine = $end; $endLine < $phpcsFile->numTokens; $endLine++) {
3✔
268
                if (isset($tokens[($endLine + 1)]) === false
3✔
269
                    || $tokens[$endLine]['line'] !== $tokens[($endLine + 1)]['line']
3✔
270
                ) {
1✔
271
                    break;
3✔
272
                }
273
            }
1✔
274

275
            if (isset(Tokens::$commentTokens[$tokens[$endLine]['code']]) === false
3✔
276
                && ($tokens[$endLine]['code'] !== T_WHITESPACE
3✔
277
                || isset(Tokens::$commentTokens[$tokens[($endLine - 1)]['code']]) === false)
3✔
278
            ) {
1✔
279
                $endLine = $end;
3✔
280
            }
1✔
281
        } else {
1✔
282
            $endLine = $end;
3✔
283
        }
284

285
        if ($endLine !== $end) {
3✔
286
            $endToken     = $endLine;
3✔
287
            $addedContent = '';
3✔
288
        } else {
1✔
289
            $endToken     = $end;
3✔
290
            $addedContent = $phpcsFile->eolChar;
3✔
291

292
            if ($tokens[$end]['code'] !== T_SEMICOLON
3✔
293
                && $tokens[$end]['code'] !== T_CLOSE_CURLY_BRACKET
3✔
294
            ) {
1✔
295
                $phpcsFile->fixer->addContent($end, '; ');
3✔
296
            }
1✔
297
        }
298

299
        $next = $phpcsFile->findNext(T_WHITESPACE, ($endToken + 1), null, true);
3✔
300
        if ($next !== false
2✔
301
            && ($tokens[$next]['code'] === T_ELSE
3✔
302
            || $tokens[$next]['code'] === T_ELSEIF)
3✔
303
        ) {
1✔
304
            $phpcsFile->fixer->addContentBefore($next, '} ');
3✔
305
        } else {
1✔
306
            $indent = '';
3✔
307
            for ($first = $stackPtr; $first > 0; $first--) {
3✔
308
                if ($tokens[$first]['column'] === 1) {
3✔
309
                    break;
3✔
310
                }
311
            }
1✔
312

313
            if ($tokens[$first]['code'] === T_WHITESPACE) {
3✔
314
                $indent = $tokens[$first]['content'];
3✔
315
            } else if ($tokens[$first]['code'] === T_INLINE_HTML
3✔
316
                || $tokens[$first]['code'] === T_OPEN_TAG
3✔
317
            ) {
1✔
318
                $addedContent = '';
3✔
319
            }
1✔
320

321
            $addedContent .= $indent.'}';
3✔
322
            if ($next !== false && $tokens[$endToken]['code'] === T_COMMENT) {
3✔
323
                $addedContent .= $phpcsFile->eolChar;
3✔
324
            }
1✔
325

326
            $phpcsFile->fixer->addContent($endToken, $addedContent);
3✔
327
        }//end if
328

329
        $phpcsFile->fixer->endChangeset();
3✔
330

331
    }//end process()
2✔
332

333

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