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

PHPCSStandards / PHP_CodeSniffer / 14309561950

07 Apr 2025 12:46PM UTC coverage: 78.707% (-0.001%) from 78.708%
14309561950

Pull #904

github

web-flow
Merge 7a19f8a22 into 99818768c
Pull Request #904: Tests/Tokenizer: use markers for the `testSwitchDefault()` test

24855 of 31579 relevant lines covered (78.71%)

67.02 hits per line

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

19.6
/src/Fixer.php
1
<?php
2
/**
3
 * A helper class for fixing errors.
4
 *
5
 * Provides helper functions that act upon a token array and modify the file
6
 * content.
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;
14

15
use InvalidArgumentException;
16
use PHP_CodeSniffer\Exceptions\RuntimeException;
17
use PHP_CodeSniffer\Files\File;
18
use PHP_CodeSniffer\Util\Common;
19

20
class Fixer
21
{
22

23
    /**
24
     * Is the fixer enabled and fixing a file?
25
     *
26
     * Sniffs should check this value to ensure they are not
27
     * doing extra processing to prepare for a fix when fixing is
28
     * not required.
29
     *
30
     * @var boolean
31
     */
32
    public $enabled = false;
33

34
    /**
35
     * The number of times we have looped over a file.
36
     *
37
     * @var integer
38
     */
39
    public $loops = 0;
40

41
    /**
42
     * The file being fixed.
43
     *
44
     * @var \PHP_CodeSniffer\Files\File
45
     */
46
    private $currentFile = null;
47

48
    /**
49
     * The list of tokens that make up the file contents.
50
     *
51
     * This is a simplified list which just contains the token content and nothing
52
     * else. This is the array that is updated as fixes are made, not the file's
53
     * token array. Imploding this array will give you the file content back.
54
     *
55
     * @var array<int, string>
56
     */
57
    private $tokens = [];
58

59
    /**
60
     * A list of tokens that have already been fixed.
61
     *
62
     * We don't allow the same token to be fixed more than once each time
63
     * through a file as this can easily cause conflicts between sniffs.
64
     *
65
     * @var int[]
66
     */
67
    private $fixedTokens = [];
68

69
    /**
70
     * The last value of each fixed token.
71
     *
72
     * If a token is being "fixed" back to its last value, the fix is
73
     * probably conflicting with another.
74
     *
75
     * @var array<int, array<string, mixed>>
76
     */
77
    private $oldTokenValues = [];
78

79
    /**
80
     * A list of tokens that have been fixed during a changeset.
81
     *
82
     * All changes in changeset must be able to be applied, or else
83
     * the entire changeset is rejected.
84
     *
85
     * @var array
86
     */
87
    private $changeset = [];
88

89
    /**
90
     * Is there an open changeset.
91
     *
92
     * @var boolean
93
     */
94
    private $inChangeset = false;
95

96
    /**
97
     * Is the current fixing loop in conflict?
98
     *
99
     * @var boolean
100
     */
101
    private $inConflict = false;
102

103
    /**
104
     * The number of fixes that have been performed.
105
     *
106
     * @var integer
107
     */
108
    private $numFixes = 0;
109

110

111
    /**
112
     * Starts fixing a new file.
113
     *
114
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being fixed.
115
     *
116
     * @return void
117
     */
118
    public function startFile(File $phpcsFile)
×
119
    {
120
        $this->currentFile = $phpcsFile;
×
121
        $this->numFixes    = 0;
×
122
        $this->fixedTokens = [];
×
123

124
        $tokens       = $phpcsFile->getTokens();
×
125
        $this->tokens = [];
×
126
        foreach ($tokens as $index => $token) {
×
127
            if (isset($token['orig_content']) === true) {
×
128
                $this->tokens[$index] = $token['orig_content'];
×
129
            } else {
130
                $this->tokens[$index] = $token['content'];
×
131
            }
132
        }
133

134
    }//end startFile()
135

136

137
    /**
138
     * Attempt to fix the file by processing it until no fixes are made.
139
     *
140
     * @return boolean
141
     */
142
    public function fixFile()
×
143
    {
144
        $fixable = $this->currentFile->getFixableCount();
×
145
        if ($fixable === 0) {
×
146
            // Nothing to fix.
147
            return false;
×
148
        }
149

150
        $this->enabled = true;
×
151

152
        $this->loops = 0;
×
153
        while ($this->loops < 50) {
×
154
            ob_start();
×
155

156
            // Only needed once file content has changed.
157
            $contents = $this->getContents();
×
158

159
            if (PHP_CODESNIFFER_VERBOSITY > 2) {
×
160
                @ob_end_clean();
×
161
                echo '---START FILE CONTENT---'.PHP_EOL;
×
162
                $lines = explode($this->currentFile->eolChar, $contents);
×
163
                $max   = strlen(count($lines));
×
164
                foreach ($lines as $lineNum => $line) {
×
165
                    $lineNum++;
×
166
                    echo str_pad($lineNum, $max, ' ', STR_PAD_LEFT).'|'.$line.PHP_EOL;
×
167
                }
168

169
                echo '--- END FILE CONTENT ---'.PHP_EOL;
×
170
                ob_start();
×
171
            }
172

173
            $this->inConflict = false;
×
174
            $this->currentFile->ruleset->populateTokenListeners();
×
175
            $this->currentFile->setContent($contents);
×
176
            $this->currentFile->process();
×
177
            ob_end_clean();
×
178

179
            $this->loops++;
×
180

181
            if (PHP_CODESNIFFER_CBF === true && PHP_CODESNIFFER_VERBOSITY > 0) {
×
182
                echo "\r".str_repeat(' ', 80)."\r";
×
183
                echo "\t=> Fixing file: $this->numFixes/$fixable violations remaining [made $this->loops pass";
×
184
                if ($this->loops > 1) {
×
185
                    echo 'es';
×
186
                }
187

188
                echo ']... ';
×
189
                if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
190
                    echo PHP_EOL;
×
191
                }
192
            }
193

194
            if ($this->numFixes === 0 && $this->inConflict === false) {
×
195
                // Nothing left to do.
196
                break;
×
197
            } else if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
198
                echo "\t* fixed $this->numFixes violations, starting loop ".($this->loops + 1).' *'.PHP_EOL;
×
199
            }
200
        }//end while
201

202
        $this->enabled = false;
×
203

204
        if ($this->numFixes > 0) {
×
205
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
206
                if (ob_get_level() > 0) {
×
207
                    ob_end_clean();
×
208
                }
209

210
                echo "\t*** Reached maximum number of loops with $this->numFixes violations left unfixed ***".PHP_EOL;
×
211
                ob_start();
×
212
            }
213

214
            return false;
×
215
        }
216

217
        return true;
×
218

219
    }//end fixFile()
220

221

222
    /**
223
     * Generates a text diff of the original file and the new content.
224
     *
225
     * @param string  $filePath Optional file path to diff the file against.
226
     *                          If not specified, the original version of the
227
     *                          file will be used.
228
     * @param boolean $colors   Print coloured output or not.
229
     *
230
     * @return string
231
     *
232
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException When the diff command fails.
233
     */
234
    public function generateDiff($filePath=null, $colors=true)
65✔
235
    {
236
        if ($filePath === null) {
65✔
237
            $filePath = $this->currentFile->getFilename();
5✔
238
        }
2✔
239

240
        $cwd = getcwd().DIRECTORY_SEPARATOR;
65✔
241
        if (strpos($filePath, $cwd) === 0) {
65✔
242
            $filename = substr($filePath, strlen($cwd));
65✔
243
        } else {
26✔
244
            $filename = $filePath;
×
245
        }
246

247
        $contents = $this->getContents();
65✔
248

249
        $tempName  = tempnam(sys_get_temp_dir(), 'phpcs-fixer');
65✔
250
        $fixedFile = fopen($tempName, 'w');
65✔
251
        fwrite($fixedFile, $contents);
65✔
252

253
        // We must use something like shell_exec() or proc_open() because whitespace at the end
254
        // of lines is critical to diff files.
255
        // Using proc_open() instead of shell_exec improves performance on Windows significantly,
256
        // while the results are the same (though more code is needed to get the results).
257
        // This is specifically due to proc_open allowing to set the "bypass_shell" option.
258
        $filename = escapeshellarg($filename);
65✔
259
        $cmd      = "diff -u -L$filename -LPHP_CodeSniffer $filename \"$tempName\"";
65✔
260

261
        // Stream 0 = STDIN, 1 = STDOUT, 2 = STDERR.
262
        $descriptorspec = [
26✔
263
            0 => [
39✔
264
                'pipe',
52✔
265
                'r',
52✔
266
            ],
52✔
267
            1 => [
26✔
268
                'pipe',
52✔
269
                'w',
52✔
270
            ],
52✔
271
            2 => [
26✔
272
                'pipe',
52✔
273
                'w',
52✔
274
            ],
52✔
275
        ];
52✔
276

277
        $options = null;
65✔
278
        if (stripos(PHP_OS, 'WIN') === 0) {
65✔
279
            $options = ['bypass_shell' => true];
26✔
280
        }
13✔
281

282
        $process = proc_open($cmd, $descriptorspec, $pipes, $cwd, null, $options);
65✔
283
        if (is_resource($process) === false) {
65✔
284
            throw new RuntimeException('Could not obtain a resource to execute the diff command.');
×
285
        }
286

287
        // We don't need these.
288
        fclose($pipes[0]);
65✔
289
        fclose($pipes[2]);
65✔
290

291
        // Stdout will contain the actual diff.
292
        $diff = stream_get_contents($pipes[1]);
65✔
293
        fclose($pipes[1]);
65✔
294

295
        proc_close($process);
65✔
296

297
        fclose($fixedFile);
65✔
298
        if (is_file($tempName) === true) {
65✔
299
            unlink($tempName);
65✔
300
        }
26✔
301

302
        if ($diff === false || $diff === '') {
65✔
303
            return '';
10✔
304
        }
305

306
        if ($colors === false) {
55✔
307
            return $diff;
50✔
308
        }
309

310
        $diffLines = explode(PHP_EOL, $diff);
5✔
311
        if (count($diffLines) === 1) {
5✔
312
            // Seems to be required for cygwin.
313
            $diffLines = explode("\n", $diff);
2✔
314
        }
1✔
315

316
        $diff = [];
5✔
317
        foreach ($diffLines as $line) {
5✔
318
            if (isset($line[0]) === true) {
5✔
319
                switch ($line[0]) {
5✔
320
                case '-':
5✔
321
                    $diff[] = "\033[31m$line\033[0m";
5✔
322
                    break;
5✔
323
                case '+':
5✔
324
                    $diff[] = "\033[32m$line\033[0m";
5✔
325
                    break;
5✔
326
                default:
2✔
327
                    $diff[] = $line;
5✔
328
                }
2✔
329
            }
2✔
330
        }
2✔
331

332
        $diff = implode(PHP_EOL, $diff);
5✔
333

334
        return $diff;
5✔
335

336
    }//end generateDiff()
337

338

339
    /**
340
     * Get a count of fixes that have been performed on the file.
341
     *
342
     * This value is reset every time a new file is started, or an existing
343
     * file is restarted.
344
     *
345
     * @return int
346
     */
347
    public function getFixCount()
×
348
    {
349
        return $this->numFixes;
×
350

351
    }//end getFixCount()
352

353

354
    /**
355
     * Get the current content of the file, as a string.
356
     *
357
     * @return string
358
     */
359
    public function getContents()
×
360
    {
361
        $contents = implode($this->tokens);
×
362
        return $contents;
×
363

364
    }//end getContents()
365

366

367
    /**
368
     * Get the current fixed content of a token.
369
     *
370
     * This function takes changesets into account so should be used
371
     * instead of directly accessing the token array.
372
     *
373
     * @param int $stackPtr The position of the token in the token stack.
374
     *
375
     * @return string
376
     */
377
    public function getTokenContent($stackPtr)
×
378
    {
379
        if ($this->inChangeset === true
×
380
            && isset($this->changeset[$stackPtr]) === true
×
381
        ) {
382
            return $this->changeset[$stackPtr];
×
383
        } else {
384
            return $this->tokens[$stackPtr];
×
385
        }
386

387
    }//end getTokenContent()
388

389

390
    /**
391
     * Start recording actions for a changeset.
392
     *
393
     * @return void|false
394
     */
395
    public function beginChangeset()
×
396
    {
397
        if ($this->inConflict === true) {
×
398
            return false;
×
399
        }
400

401
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
402
            $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
×
403
            if ($bt[1]['class'] === __CLASS__) {
×
404
                $sniff = 'Fixer';
×
405
            } else {
406
                $sniff = $this->getSniffCodeForDebug($bt[1]['class']);
×
407
            }
408

409
            $line = $bt[0]['line'];
×
410

411
            @ob_end_clean();
×
412
            echo "\t=> Changeset started by $sniff:$line".PHP_EOL;
×
413
            ob_start();
×
414
        }
415

416
        $this->changeset   = [];
×
417
        $this->inChangeset = true;
×
418

419
    }//end beginChangeset()
420

421

422
    /**
423
     * Stop recording actions for a changeset, and apply logged changes.
424
     *
425
     * @return boolean
426
     */
427
    public function endChangeset()
×
428
    {
429
        if ($this->inConflict === true) {
×
430
            return false;
×
431
        }
432

433
        $this->inChangeset = false;
×
434

435
        $success = true;
×
436
        $applied = [];
×
437
        foreach ($this->changeset as $stackPtr => $content) {
×
438
            $success = $this->replaceToken($stackPtr, $content);
×
439
            if ($success === false) {
×
440
                break;
×
441
            } else {
442
                $applied[] = $stackPtr;
×
443
            }
444
        }
445

446
        if ($success === false) {
×
447
            // Rolling back all changes.
448
            foreach ($applied as $stackPtr) {
×
449
                $this->revertToken($stackPtr);
×
450
            }
451

452
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
453
                @ob_end_clean();
×
454
                echo "\t=> Changeset failed to apply".PHP_EOL;
×
455
                ob_start();
×
456
            }
457
        } else if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
458
            $fixes = count($this->changeset);
×
459
            @ob_end_clean();
×
460
            echo "\t=> Changeset ended: $fixes changes applied".PHP_EOL;
×
461
            ob_start();
×
462
        }
463

464
        $this->changeset = [];
×
465
        return true;
×
466

467
    }//end endChangeset()
468

469

470
    /**
471
     * Stop recording actions for a changeset, and discard logged changes.
472
     *
473
     * @return void
474
     */
475
    public function rollbackChangeset()
×
476
    {
477
        $this->inChangeset = false;
×
478
        $this->inConflict  = false;
×
479

480
        if (empty($this->changeset) === false) {
×
481
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
482
                $bt = debug_backtrace();
×
483
                if ($bt[1]['class'] === 'PHP_CodeSniffer\Fixer') {
×
484
                    $sniff = $bt[2]['class'];
×
485
                    $line  = $bt[1]['line'];
×
486
                } else {
487
                    $sniff = $bt[1]['class'];
×
488
                    $line  = $bt[0]['line'];
×
489
                }
490

491
                $sniff = $this->getSniffCodeForDebug($sniff);
×
492

493
                $numChanges = count($this->changeset);
×
494

495
                @ob_end_clean();
×
496
                echo "\t\tR: $sniff:$line rolled back the changeset ($numChanges changes)".PHP_EOL;
×
497
                echo "\t=> Changeset rolled back".PHP_EOL;
×
498
                ob_start();
×
499
            }
500

501
            $this->changeset = [];
×
502
        }//end if
503

504
    }//end rollbackChangeset()
505

506

507
    /**
508
     * Replace the entire contents of a token.
509
     *
510
     * @param int    $stackPtr The position of the token in the token stack.
511
     * @param string $content  The new content of the token.
512
     *
513
     * @return bool If the change was accepted.
514
     */
515
    public function replaceToken($stackPtr, $content)
×
516
    {
517
        if ($this->inConflict === true) {
×
518
            return false;
×
519
        }
520

521
        if ($this->inChangeset === false
×
522
            && isset($this->fixedTokens[$stackPtr]) === true
×
523
        ) {
524
            $indent = "\t";
×
525
            if (empty($this->changeset) === false) {
×
526
                $indent .= "\t";
×
527
            }
528

529
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
530
                @ob_end_clean();
×
531
                echo "$indent* token $stackPtr has already been modified, skipping *".PHP_EOL;
×
532
                ob_start();
×
533
            }
534

535
            return false;
×
536
        }
537

538
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
539
            $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
×
540
            if ($bt[1]['class'] === 'PHP_CodeSniffer\Fixer') {
×
541
                $sniff = $bt[2]['class'];
×
542
                $line  = $bt[1]['line'];
×
543
            } else {
544
                $sniff = $bt[1]['class'];
×
545
                $line  = $bt[0]['line'];
×
546
            }
547

548
            $sniff = $this->getSniffCodeForDebug($sniff);
×
549

550
            $tokens     = $this->currentFile->getTokens();
×
551
            $type       = $tokens[$stackPtr]['type'];
×
552
            $tokenLine  = $tokens[$stackPtr]['line'];
×
553
            $oldContent = Common::prepareForOutput($this->tokens[$stackPtr]);
×
554
            $newContent = Common::prepareForOutput($content);
×
555
            if (trim($this->tokens[$stackPtr]) === '' && isset($this->tokens[($stackPtr + 1)]) === true) {
×
556
                // Add some context for whitespace only changes.
557
                $append      = Common::prepareForOutput($this->tokens[($stackPtr + 1)]);
×
558
                $oldContent .= $append;
×
559
                $newContent .= $append;
×
560
            }
561
        }//end if
562

563
        if ($this->inChangeset === true) {
×
564
            $this->changeset[$stackPtr] = $content;
×
565

566
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
567
                @ob_end_clean();
×
568
                echo "\t\tQ: $sniff:$line replaced token $stackPtr ($type on line $tokenLine) \"$oldContent\" => \"$newContent\"".PHP_EOL;
×
569
                ob_start();
×
570
            }
571

572
            return true;
×
573
        }
574

575
        if (isset($this->oldTokenValues[$stackPtr]) === false) {
×
576
            $this->oldTokenValues[$stackPtr] = [
×
577
                'curr' => $content,
×
578
                'prev' => $this->tokens[$stackPtr],
×
579
                'loop' => $this->loops,
×
580
            ];
581
        } else {
582
            if ($this->oldTokenValues[$stackPtr]['prev'] === $content
×
583
                && $this->oldTokenValues[$stackPtr]['loop'] === ($this->loops - 1)
×
584
            ) {
585
                if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
586
                    $indent = "\t";
×
587
                    if (empty($this->changeset) === false) {
×
588
                        $indent .= "\t";
×
589
                    }
590

591
                    $loop = $this->oldTokenValues[$stackPtr]['loop'];
×
592

593
                    @ob_end_clean();
×
594
                    echo "$indent**** $sniff:$line has possible conflict with another sniff on loop $loop; caused by the following change ****".PHP_EOL;
×
595
                    echo "$indent**** replaced token $stackPtr ($type on line $tokenLine) \"$oldContent\" => \"$newContent\" ****".PHP_EOL;
×
596
                }
597

598
                if ($this->oldTokenValues[$stackPtr]['loop'] >= ($this->loops - 1)) {
×
599
                    $this->inConflict = true;
×
600
                    if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
601
                        echo "$indent**** ignoring all changes until next loop ****".PHP_EOL;
×
602
                    }
603
                }
604

605
                if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
606
                    ob_start();
×
607
                }
608

609
                return false;
×
610
            }//end if
611

612
            $this->oldTokenValues[$stackPtr]['prev'] = $this->oldTokenValues[$stackPtr]['curr'];
×
613
            $this->oldTokenValues[$stackPtr]['curr'] = $content;
×
614
            $this->oldTokenValues[$stackPtr]['loop'] = $this->loops;
×
615
        }//end if
616

617
        $this->fixedTokens[$stackPtr] = $this->tokens[$stackPtr];
×
618
        $this->tokens[$stackPtr]      = $content;
×
619
        $this->numFixes++;
×
620

621
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
622
            $indent = "\t";
×
623
            if (empty($this->changeset) === false) {
×
624
                $indent .= "\tA: ";
×
625
            }
626

627
            if (ob_get_level() > 0) {
×
628
                ob_end_clean();
×
629
            }
630

631
            echo "$indent$sniff:$line replaced token $stackPtr ($type on line $tokenLine) \"$oldContent\" => \"$newContent\"".PHP_EOL;
×
632
            ob_start();
×
633
        }
634

635
        return true;
×
636

637
    }//end replaceToken()
638

639

640
    /**
641
     * Reverts the previous fix made to a token.
642
     *
643
     * @param int $stackPtr The position of the token in the token stack.
644
     *
645
     * @return bool If a change was reverted.
646
     */
647
    public function revertToken($stackPtr)
×
648
    {
649
        if (isset($this->fixedTokens[$stackPtr]) === false) {
×
650
            return false;
×
651
        }
652

653
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
654
            $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
×
655
            if ($bt[1]['class'] === 'PHP_CodeSniffer\Fixer') {
×
656
                $sniff = $bt[2]['class'];
×
657
                $line  = $bt[1]['line'];
×
658
            } else {
659
                $sniff = $bt[1]['class'];
×
660
                $line  = $bt[0]['line'];
×
661
            }
662

663
            $sniff = $this->getSniffCodeForDebug($sniff);
×
664

665
            $tokens     = $this->currentFile->getTokens();
×
666
            $type       = $tokens[$stackPtr]['type'];
×
667
            $tokenLine  = $tokens[$stackPtr]['line'];
×
668
            $oldContent = Common::prepareForOutput($this->tokens[$stackPtr]);
×
669
            $newContent = Common::prepareForOutput($this->fixedTokens[$stackPtr]);
×
670
            if (trim($this->tokens[$stackPtr]) === '' && isset($tokens[($stackPtr + 1)]) === true) {
×
671
                // Add some context for whitespace only changes.
672
                $append      = Common::prepareForOutput($this->tokens[($stackPtr + 1)]);
×
673
                $oldContent .= $append;
×
674
                $newContent .= $append;
×
675
            }
676
        }//end if
677

678
        $this->tokens[$stackPtr] = $this->fixedTokens[$stackPtr];
×
679
        unset($this->fixedTokens[$stackPtr]);
×
680
        $this->numFixes--;
×
681

682
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
683
            $indent = "\t";
×
684
            if (empty($this->changeset) === false) {
×
685
                $indent .= "\tR: ";
×
686
            }
687

688
            @ob_end_clean();
×
689
            echo "$indent$sniff:$line reverted token $stackPtr ($type on line $tokenLine) \"$oldContent\" => \"$newContent\"".PHP_EOL;
×
690
            ob_start();
×
691
        }
692

693
        return true;
×
694

695
    }//end revertToken()
696

697

698
    /**
699
     * Replace the content of a token with a part of its current content.
700
     *
701
     * @param int $stackPtr The position of the token in the token stack.
702
     * @param int $start    The first character to keep.
703
     * @param int $length   The number of characters to keep. If NULL, the content of
704
     *                      the token from $start to the end of the content is kept.
705
     *
706
     * @return bool If the change was accepted.
707
     */
708
    public function substrToken($stackPtr, $start, $length=null)
×
709
    {
710
        $current = $this->getTokenContent($stackPtr);
×
711

712
        if ($length === null) {
×
713
            $newContent = substr($current, $start);
×
714
        } else {
715
            $newContent = substr($current, $start, $length);
×
716
        }
717

718
        return $this->replaceToken($stackPtr, $newContent);
×
719

720
    }//end substrToken()
721

722

723
    /**
724
     * Adds a newline to end of a token's content.
725
     *
726
     * @param int $stackPtr The position of the token in the token stack.
727
     *
728
     * @return bool If the change was accepted.
729
     */
730
    public function addNewline($stackPtr)
×
731
    {
732
        $current = $this->getTokenContent($stackPtr);
×
733
        return $this->replaceToken($stackPtr, $current.$this->currentFile->eolChar);
×
734

735
    }//end addNewline()
736

737

738
    /**
739
     * Adds a newline to the start of a token's content.
740
     *
741
     * @param int $stackPtr The position of the token in the token stack.
742
     *
743
     * @return bool If the change was accepted.
744
     */
745
    public function addNewlineBefore($stackPtr)
×
746
    {
747
        $current = $this->getTokenContent($stackPtr);
×
748
        return $this->replaceToken($stackPtr, $this->currentFile->eolChar.$current);
×
749

750
    }//end addNewlineBefore()
751

752

753
    /**
754
     * Adds content to the end of a token's current content.
755
     *
756
     * @param int    $stackPtr The position of the token in the token stack.
757
     * @param string $content  The content to add.
758
     *
759
     * @return bool If the change was accepted.
760
     */
761
    public function addContent($stackPtr, $content)
×
762
    {
763
        $current = $this->getTokenContent($stackPtr);
×
764
        return $this->replaceToken($stackPtr, $current.$content);
×
765

766
    }//end addContent()
767

768

769
    /**
770
     * Adds content to the start of a token's current content.
771
     *
772
     * @param int    $stackPtr The position of the token in the token stack.
773
     * @param string $content  The content to add.
774
     *
775
     * @return bool If the change was accepted.
776
     */
777
    public function addContentBefore($stackPtr, $content)
×
778
    {
779
        $current = $this->getTokenContent($stackPtr);
×
780
        return $this->replaceToken($stackPtr, $content.$current);
×
781

782
    }//end addContentBefore()
783

784

785
    /**
786
     * Adjust the indent of a code block.
787
     *
788
     * @param int $start  The position of the token in the token stack
789
     *                    to start adjusting the indent from.
790
     * @param int $end    The position of the token in the token stack
791
     *                    to end adjusting the indent.
792
     * @param int $change The number of spaces to adjust the indent by
793
     *                    (positive or negative).
794
     *
795
     * @return void
796
     */
797
    public function changeCodeBlockIndent($start, $end, $change)
×
798
    {
799
        $tokens = $this->currentFile->getTokens();
×
800

801
        $baseIndent = '';
×
802
        if ($change > 0) {
×
803
            $baseIndent = str_repeat(' ', $change);
×
804
        }
805

806
        $useChangeset = false;
×
807
        if ($this->inChangeset === false) {
×
808
            $this->beginChangeset();
×
809
            $useChangeset = true;
×
810
        }
811

812
        for ($i = $start; $i <= $end; $i++) {
×
813
            if ($tokens[$i]['column'] !== 1
×
814
                || $tokens[($i + 1)]['line'] !== $tokens[$i]['line']
×
815
            ) {
816
                continue;
×
817
            }
818

819
            $length = 0;
×
820
            if ($tokens[$i]['code'] === T_WHITESPACE
×
821
                || $tokens[$i]['code'] === T_DOC_COMMENT_WHITESPACE
×
822
            ) {
823
                $length = $tokens[$i]['length'];
×
824

825
                $padding = ($length + $change);
×
826
                if ($padding > 0) {
×
827
                    $padding = str_repeat(' ', $padding);
×
828
                } else {
829
                    $padding = '';
×
830
                }
831

832
                $newContent = $padding.ltrim($tokens[$i]['content']);
×
833
            } else {
834
                $newContent = $baseIndent.$tokens[$i]['content'];
×
835
            }
836

837
            $this->replaceToken($i, $newContent);
×
838
        }//end for
839

840
        if ($useChangeset === true) {
×
841
            $this->endChangeset();
×
842
        }
843

844
    }//end changeCodeBlockIndent()
845

846

847
    /**
848
     * Get the sniff code for the current sniff or the class name if the passed class is not a sniff.
849
     *
850
     * @param string $className Class name.
851
     *
852
     * @return string
853
     */
854
    private function getSniffCodeForDebug($className)
×
855
    {
856
        try {
857
            $sniffCode = Common::getSniffCode($className);
×
858
            return $sniffCode;
×
859
        } catch (InvalidArgumentException $e) {
×
860
            // Sniff code could not be determined. This may be an abstract sniff class or a helper class.
861
            return $className;
×
862
        }
863

864
    }//end getSniffCodeForDebug()
865

866

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