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

PHPCSStandards / PHP_CodeSniffer / 17663621563

12 Sep 2025 03:25AM UTC coverage: 78.786%. Remained the same
17663621563

push

github

web-flow
Merge pull request #1243 from PHPCSStandards/phpcs-4.x/feature/155-normalize-some-code-style-rules-5

CS: normalize code style rules [5]

294 of 308 new or added lines in 191 files covered. (95.45%)

2354 existing lines in 130 files now uncovered.

19732 of 25045 relevant lines covered (78.79%)

96.47 hits per line

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

94.12
/src/Standards/Generic/Sniffs/Formatting/MultipleStatementAlignmentSniff.php
1
<?php
2
/**
3
 * Checks alignment of assignments.
4
 *
5
 * If there are multiple adjacent assignments, it will check that the equals signs of
6
 * each assignment are aligned. It will display a warning to advise that the signs should be aligned.
7
 *
8
 * @author    Greg Sherwood <gsherwood@squiz.net>
9
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
10
 * @license   https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
11
 */
12

13
namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting;
14

15
use PHP_CodeSniffer\Files\File;
16
use PHP_CodeSniffer\Sniffs\Sniff;
17
use PHP_CodeSniffer\Util\Tokens;
18

19
class MultipleStatementAlignmentSniff implements Sniff
20
{
21

22
    /**
23
     * The maximum amount of padding before the alignment is ignored.
24
     *
25
     * If the amount of padding required to align this assignment with the
26
     * surrounding assignments exceeds this number, the assignment will be
27
     * ignored and no errors or warnings will be thrown.
28
     *
29
     * @var integer
30
     */
31
    public $maxPadding = 1000;
32

33
    /**
34
     * Controls which side of the assignment token is used for alignment.
35
     *
36
     * @var boolean
37
     */
38
    public $alignAtEnd = true;
39

40

41
    /**
42
     * Returns an array of tokens this test wants to listen for.
43
     *
44
     * @return array<int|string>
45
     */
46
    public function register()
3✔
47
    {
48
        $tokens = Tokens::ASSIGNMENT_TOKENS;
3✔
49
        unset($tokens[T_DOUBLE_ARROW]);
3✔
50
        return $tokens;
3✔
51
    }
52

53

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

69

70
    /**
71
     * Processes this test, when one of its tokens is encountered.
72
     *
73
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
74
     * @param int                         $stackPtr  The position of the current token
75
     *                                               in the stack passed in $tokens.
76
     * @param int|null                    $end       The token where checking should end.
77
     *                                               If NULL, the entire file will be checked.
78
     *
79
     * @return int
80
     */
81
    public function checkAlignment(File $phpcsFile, int $stackPtr, ?int $end = null)
3✔
82
    {
83
        $tokens = $phpcsFile->getTokens();
3✔
84

85
        // Ignore assignments used in a condition, like an IF or FOR or closure param defaults.
86
        if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
3✔
87
            // If the parenthesis is on the same line as the assignment,
88
            // then it should be ignored as it is specifically being grouped.
89
            $parens    = $tokens[$stackPtr]['nested_parenthesis'];
3✔
90
            $lastParen = array_pop($parens);
3✔
91
            if ($tokens[$lastParen]['line'] === $tokens[$stackPtr]['line']) {
3✔
92
                return $stackPtr;
3✔
93
            }
94

95
            foreach ($tokens[$stackPtr]['nested_parenthesis'] as $start => $end) {
3✔
96
                if (isset($tokens[$start]['parenthesis_owner']) === true) {
3✔
UNCOV
97
                    return $stackPtr;
×
98
                }
99
            }
100
        }
101

102
        $assignments = [];
3✔
103
        $prevAssign  = null;
3✔
104
        $lastLine    = $tokens[$stackPtr]['line'];
3✔
105
        $maxPadding  = null;
3✔
106
        $stopped     = null;
3✔
107
        $lastCode    = $stackPtr;
3✔
108
        $lastSemi    = null;
3✔
109
        $arrayEnd    = null;
3✔
110

111
        if ($end === null) {
3✔
112
            $end = $phpcsFile->numTokens;
3✔
113
        }
114

115
        $find = Tokens::ASSIGNMENT_TOKENS;
3✔
116
        unset($find[T_DOUBLE_ARROW]);
3✔
117

118
        $scopes = Tokens::SCOPE_OPENERS;
3✔
119
        unset($scopes[T_CLOSURE]);
3✔
120
        unset($scopes[T_ANON_CLASS]);
3✔
121

122
        for ($assign = $stackPtr; $assign < $end; $assign++) {
3✔
123
            if ($tokens[$assign]['level'] < $tokens[$stackPtr]['level']) {
3✔
124
                // Statement is in a different context, so the block is over.
125
                break;
3✔
126
            }
127

128
            if (isset($tokens[$assign]['scope_opener']) === true
3✔
129
                && $tokens[$assign]['level'] === $tokens[$stackPtr]['level']
3✔
130
            ) {
131
                if (isset($scopes[$tokens[$assign]['code']]) === true) {
3✔
132
                    // This type of scope indicates that the assignment block is over.
133
                    break;
3✔
134
                }
135

136
                // Skip over the scope block because it is seen as part of the assignment block,
137
                // but also process any assignment blocks that are inside as well.
138
                $nextAssign = $phpcsFile->findNext($find, ($assign + 1), ($tokens[$assign]['scope_closer'] - 1));
3✔
139
                if ($nextAssign !== false) {
3✔
140
                    $assign = $this->checkAlignment($phpcsFile, $nextAssign);
3✔
141
                } else {
142
                    $assign = $tokens[$assign]['scope_closer'];
3✔
143
                }
144

145
                $lastCode = $assign;
3✔
146
                continue;
3✔
147
            }
148

149
            if ($assign === $arrayEnd) {
3✔
150
                $arrayEnd = null;
3✔
151
            }
152

153
            if (isset($find[$tokens[$assign]['code']]) === false) {
3✔
154
                // A blank line indicates that the assignment block has ended.
155
                if (isset(Tokens::EMPTY_TOKENS[$tokens[$assign]['code']]) === false
3✔
156
                    && ($tokens[$assign]['line'] - $tokens[$lastCode]['line']) > 1
3✔
157
                    && $tokens[$assign]['level'] === $tokens[$stackPtr]['level']
3✔
158
                    && $arrayEnd === null
3✔
159
                ) {
160
                    break;
3✔
161
                }
162

163
                if ($tokens[$assign]['code'] === T_CLOSE_TAG) {
3✔
164
                    // Breaking out of PHP ends the assignment block.
165
                    break;
3✔
166
                }
167

168
                if ($tokens[$assign]['code'] === T_OPEN_SHORT_ARRAY
3✔
169
                    && isset($tokens[$assign]['bracket_closer']) === true
3✔
170
                ) {
171
                    $arrayEnd = $tokens[$assign]['bracket_closer'];
3✔
172
                }
173

174
                if ($tokens[$assign]['code'] === T_ARRAY
3✔
175
                    && isset($tokens[$assign]['parenthesis_opener']) === true
3✔
176
                    && isset($tokens[$tokens[$assign]['parenthesis_opener']]['parenthesis_closer']) === true
3✔
177
                ) {
178
                    $arrayEnd = $tokens[$tokens[$assign]['parenthesis_opener']]['parenthesis_closer'];
3✔
179
                }
180

181
                if (isset(Tokens::EMPTY_TOKENS[$tokens[$assign]['code']]) === false) {
3✔
182
                    $lastCode = $assign;
3✔
183

184
                    if ($tokens[$assign]['code'] === T_SEMICOLON) {
3✔
185
                        if ($tokens[$assign]['conditions'] === $tokens[$stackPtr]['conditions']) {
3✔
186
                            if ($lastSemi !== null && $prevAssign !== null && $lastSemi > $prevAssign) {
3✔
187
                                // This statement did not have an assignment operator in it.
188
                                break;
3✔
189
                            } else {
190
                                $lastSemi = $assign;
3✔
191
                            }
192
                        } elseif ($tokens[$assign]['level'] < $tokens[$stackPtr]['level']) {
3✔
193
                            // Statement is in a different context, so the block is over.
UNCOV
194
                            break;
×
195
                        }
196
                    }
197
                }//end if
198

199
                continue;
3✔
200
            } elseif ($assign !== $stackPtr && $tokens[$assign]['line'] === $lastLine) {
3✔
201
                // Skip multiple assignments on the same line. We only need to
202
                // try and align the first assignment.
203
                continue;
3✔
204
            }//end if
205

206
            if ($assign !== $stackPtr) {
3✔
207
                if ($tokens[$assign]['level'] > $tokens[$stackPtr]['level']) {
3✔
208
                    // Has to be nested inside the same conditions as the first assignment.
209
                    // We've gone one level down, so process this new block.
210
                    $assign   = $this->checkAlignment($phpcsFile, $assign);
3✔
211
                    $lastCode = $assign;
3✔
212
                    continue;
3✔
213
                } elseif ($tokens[$assign]['level'] < $tokens[$stackPtr]['level']) {
3✔
214
                    // We've gone one level up, so the block we are processing is done.
UNCOV
215
                    break;
×
216
                } elseif ($arrayEnd !== null) {
3✔
217
                    // Assignments inside arrays are not part of
218
                    // the original block, so process this new block.
219
                    $assign   = ($this->checkAlignment($phpcsFile, $assign, $arrayEnd) - 1);
3✔
220
                    $arrayEnd = null;
3✔
221
                    $lastCode = $assign;
3✔
222
                    continue;
3✔
223
                }
224

225
                // Make sure it is not assigned inside a condition (eg. IF, FOR).
226
                if (isset($tokens[$assign]['nested_parenthesis']) === true) {
3✔
227
                    // If the parenthesis is on the same line as the assignment,
228
                    // then it should be ignored as it is specifically being grouped.
229
                    $parens    = $tokens[$assign]['nested_parenthesis'];
3✔
230
                    $lastParen = array_pop($parens);
3✔
231
                    if ($tokens[$lastParen]['line'] === $tokens[$assign]['line']) {
3✔
232
                        break;
3✔
233
                    }
234

235
                    foreach ($tokens[$assign]['nested_parenthesis'] as $start => $end) {
3✔
236
                        if (isset($tokens[$start]['parenthesis_owner']) === true) {
3✔
UNCOV
237
                            break(2);
×
238
                        }
239
                    }
240
                }
241
            }//end if
242

243
            $var = $phpcsFile->findPrevious(
3✔
244
                Tokens::EMPTY_TOKENS,
3✔
245
                ($assign - 1),
3✔
246
                null,
3✔
247
                true
3✔
248
            );
2✔
249

250
            // Make sure we wouldn't break our max padding length if we
251
            // aligned with this statement, or they wouldn't break the max
252
            // padding length if they aligned with us.
253
            $varEnd    = $tokens[($var + 1)]['column'];
3✔
254
            $assignLen = $tokens[$assign]['length'];
3✔
255
            if ($this->alignAtEnd !== true) {
3✔
256
                $assignLen = 1;
3✔
257
            }
258

259
            if ($assign !== $stackPtr) {
3✔
260
                if ($prevAssign === null) {
3✔
261
                    // Processing an inner block but no assignments found.
UNCOV
262
                    break;
×
263
                }
264

265
                if (($varEnd + 1) > $assignments[$prevAssign]['assign_col']) {
3✔
266
                    $padding      = 1;
3✔
267
                    $assignColumn = ($varEnd + 1);
3✔
268
                } else {
269
                    $padding = ($assignments[$prevAssign]['assign_col'] - $varEnd + $assignments[$prevAssign]['assign_len'] - $assignLen);
3✔
270
                    if ($padding <= 0) {
3✔
271
                        $padding = 1;
3✔
272
                    }
273

274
                    if ($padding > $this->maxPadding) {
3✔
UNCOV
275
                        $stopped = $assign;
×
UNCOV
276
                        break;
×
277
                    }
278

279
                    $assignColumn = ($varEnd + $padding);
3✔
280
                }//end if
281

282
                if (($assignColumn + $assignLen) > ($assignments[$maxPadding]['assign_col'] + $assignments[$maxPadding]['assign_len'])) {
3✔
283
                    $newPadding = ($varEnd - $assignments[$maxPadding]['var_end'] + $assignLen - $assignments[$maxPadding]['assign_len'] + 1);
3✔
284
                    if ($newPadding > $this->maxPadding) {
3✔
285
                        $stopped = $assign;
3✔
286
                        break;
3✔
287
                    } else {
288
                        // New alignment settings for previous assignments.
289
                        foreach ($assignments as $i => $data) {
3✔
290
                            if ($i === $assign) {
3✔
UNCOV
291
                                break;
×
292
                            }
293

294
                            $newPadding = ($varEnd - $data['var_end'] + $assignLen - $data['assign_len'] + 1);
3✔
295
                            $assignments[$i]['expected']   = $newPadding;
3✔
296
                            $assignments[$i]['assign_col'] = ($data['var_end'] + $newPadding);
3✔
297
                        }
298

299
                        $padding      = 1;
3✔
300
                        $assignColumn = ($varEnd + 1);
3✔
301
                    }
302
                } elseif ($padding > $assignments[$maxPadding]['expected']) {
3✔
303
                    $maxPadding = $assign;
3✔
304
                }//end if
305
            } else {
306
                $padding      = 1;
3✔
307
                $assignColumn = ($varEnd + 1);
3✔
308
                $maxPadding   = $assign;
3✔
309
            }//end if
310

311
            $found = 0;
3✔
312
            if ($tokens[($var + 1)]['code'] === T_WHITESPACE) {
3✔
313
                $found = $tokens[($var + 1)]['length'];
3✔
314
                if ($found === 0) {
3✔
315
                    // This means a newline was found.
UNCOV
316
                    $found = 1;
×
317
                }
318
            }
319

320
            $assignments[$assign] = [
3✔
321
                'var_end'    => $varEnd,
3✔
322
                'assign_len' => $assignLen,
3✔
323
                'assign_col' => $assignColumn,
3✔
324
                'expected'   => $padding,
3✔
325
                'found'      => $found,
3✔
326
            ];
2✔
327

328
            $lastLine   = $tokens[$assign]['line'];
3✔
329
            $prevAssign = $assign;
3✔
330
        }//end for
331

332
        if (empty($assignments) === true) {
3✔
UNCOV
333
            return $stackPtr;
×
334
        }
335

336
        $numAssignments = count($assignments);
3✔
337

338
        $errorGenerated = false;
3✔
339
        foreach ($assignments as $assignment => $data) {
3✔
340
            if ($data['found'] === $data['expected']) {
3✔
341
                continue;
3✔
342
            }
343

344
            $expectedText = $data['expected'] . ' space';
3✔
345
            if ($data['expected'] !== 1) {
3✔
346
                $expectedText .= 's';
3✔
347
            }
348

349
            if ($data['found'] === null) {
3✔
UNCOV
350
                $foundText = 'a new line';
×
351
            } else {
352
                $foundText = $data['found'] . ' space';
3✔
353
                if ($data['found'] !== 1) {
3✔
354
                    $foundText .= 's';
3✔
355
                }
356
            }
357

358
            if ($numAssignments === 1) {
3✔
359
                $type  = 'Incorrect';
3✔
360
                $error = 'Equals sign not aligned correctly; expected %s but found %s';
3✔
361
            } else {
362
                $type  = 'NotSame';
3✔
363
                $error = 'Equals sign not aligned with surrounding assignments; expected %s but found %s';
3✔
364
            }
365

366
            $errorData = [
2✔
367
                $expectedText,
3✔
368
                $foundText,
3✔
369
            ];
2✔
370

371
            $fix = $phpcsFile->addFixableWarning($error, $assignment, $type, $errorData);
3✔
372

373
            $errorGenerated = true;
3✔
374

375
            if ($fix === true && $data['found'] !== null) {
3✔
376
                $newContent = str_repeat(' ', $data['expected']);
3✔
377
                if ($data['found'] === 0) {
3✔
378
                    $phpcsFile->fixer->addContentBefore($assignment, $newContent);
3✔
379
                } else {
380
                    $phpcsFile->fixer->replaceToken(($assignment - 1), $newContent);
3✔
381
                }
382
            }
383
        }//end foreach
384

385
        if ($numAssignments > 1) {
3✔
386
            if ($errorGenerated === true) {
3✔
387
                $phpcsFile->recordMetric($stackPtr, 'Adjacent assignments aligned', 'no');
3✔
388
            } else {
389
                $phpcsFile->recordMetric($stackPtr, 'Adjacent assignments aligned', 'yes');
3✔
390
            }
391
        }
392

393
        if ($stopped !== null) {
3✔
394
            return $this->checkAlignment($phpcsFile, $stopped);
3✔
395
        } else {
396
            return $assign;
3✔
397
        }
398
    }
399
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc