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

keradus / PHP-CS-Fixer / 16999983712

15 Aug 2025 09:42PM UTC coverage: 94.75% (-0.09%) from 94.839%
16999983712

push

github

keradus
ci: more self-fixing checks on lowest/highest PHP

28263 of 29829 relevant lines covered (94.75%)

45.88 hits per line

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

98.15
/src/Fixer/ControlStructure/YodaStyleFixer.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of PHP CS Fixer.
7
 *
8
 * (c) Fabien Potencier <fabien@symfony.com>
9
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14

15
namespace PhpCsFixer\Fixer\ControlStructure;
16

17
use PhpCsFixer\AbstractFixer;
18
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
19
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
20
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
21
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
22
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
23
use PhpCsFixer\FixerDefinition\CodeSample;
24
use PhpCsFixer\FixerDefinition\FixerDefinition;
25
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
26
use PhpCsFixer\Tokenizer\CT;
27
use PhpCsFixer\Tokenizer\Token;
28
use PhpCsFixer\Tokenizer\Tokens;
29
use PhpCsFixer\Tokenizer\TokensAnalyzer;
30

31
/**
32
 * @phpstan-type _AutogeneratedInputConfiguration array{
33
 *  always_move_variable?: bool,
34
 *  equal?: bool|null,
35
 *  identical?: bool|null,
36
 *  less_and_greater?: bool|null,
37
 * }
38
 * @phpstan-type _AutogeneratedComputedConfiguration array{
39
 *  always_move_variable: bool,
40
 *  equal: bool|null,
41
 *  identical: bool|null,
42
 *  less_and_greater: bool|null,
43
 * }
44
 *
45
 * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
46
 *
47
 * @author Bram Gotink <bram@gotink.me>
48
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
49
 */
50
final class YodaStyleFixer extends AbstractFixer implements ConfigurableFixerInterface
51
{
52
    /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
53
    use ConfigurableFixerTrait;
54

55
    /**
56
     * @var array<int|string, Token>
57
     */
58
    private array $candidatesMap;
59

60
    /**
61
     * @var array<int|string, null|bool>
62
     */
63
    private array $candidateTypesConfiguration;
64

65
    /**
66
     * @var list<int|string>
67
     */
68
    private array $candidateTypes;
69

70
    public function getDefinition(): FixerDefinitionInterface
71
    {
72
        return new FixerDefinition(
3✔
73
            'Write conditions in Yoda style (`true`), non-Yoda style (`[\'equal\' => false, \'identical\' => false, \'less_and_greater\' => false]`) or ignore those conditions (`null`) based on configuration.',
3✔
74
            [
3✔
75
                new CodeSample(
3✔
76
                    '<?php
3✔
77
    if ($a === null) {
78
        echo "null";
79
    }
80
'
3✔
81
                ),
3✔
82
                new CodeSample(
3✔
83
                    '<?php
3✔
84
    $b = $c != 1;  // equal
85
    $a = 1 === $b; // identical
86
    $c = $c > 3;   // less than
87
',
3✔
88
                    [
3✔
89
                        'equal' => true,
3✔
90
                        'identical' => false,
3✔
91
                        'less_and_greater' => null,
3✔
92
                    ]
3✔
93
                ),
3✔
94
                new CodeSample(
3✔
95
                    '<?php
3✔
96
return $foo === count($bar);
97
',
3✔
98
                    [
3✔
99
                        'always_move_variable' => true,
3✔
100
                    ]
3✔
101
                ),
3✔
102
                new CodeSample(
3✔
103
                    '<?php
3✔
104
    // Enforce non-Yoda style.
105
    if (null === $a) {
106
        echo "null";
107
    }
108
',
3✔
109
                    [
3✔
110
                        'equal' => false,
3✔
111
                        'identical' => false,
3✔
112
                        'less_and_greater' => false,
3✔
113
                    ]
3✔
114
                ),
3✔
115
            ]
3✔
116
        );
3✔
117
    }
118

119
    /**
120
     * {@inheritdoc}
121
     *
122
     * Must run after IsNullFixer.
123
     */
124
    public function getPriority(): int
125
    {
126
        return 0;
1✔
127
    }
128

129
    public function isCandidate(Tokens $tokens): bool
130
    {
131
        return $tokens->isAnyTokenKindsFound($this->candidateTypes);
415✔
132
    }
133

134
    protected function configurePostNormalisation(): void
135
    {
136
        $this->resolveConfiguration();
426✔
137
    }
138

139
    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
140
    {
141
        $this->fixTokens($tokens);
403✔
142
    }
143

144
    protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
145
    {
146
        return new FixerConfigurationResolver([
426✔
147
            (new FixerOptionBuilder('equal', 'Style for equal (`==`, `!=`) statements.'))
426✔
148
                ->setAllowedTypes(['bool', 'null'])
426✔
149
                ->setDefault(true)
426✔
150
                ->getOption(),
426✔
151
            (new FixerOptionBuilder('identical', 'Style for identical (`===`, `!==`) statements.'))
426✔
152
                ->setAllowedTypes(['bool', 'null'])
426✔
153
                ->setDefault(true)
426✔
154
                ->getOption(),
426✔
155
            (new FixerOptionBuilder('less_and_greater', 'Style for less and greater than (`<`, `<=`, `>`, `>=`) statements.'))
426✔
156
                ->setAllowedTypes(['bool', 'null'])
426✔
157
                ->setDefault(null)
426✔
158
                ->getOption(),
426✔
159
            (new FixerOptionBuilder('always_move_variable', 'Whether variables should always be on non assignable side when applying Yoda style.'))
426✔
160
                ->setAllowedTypes(['bool'])
426✔
161
                ->setDefault(false)
426✔
162
                ->getOption(),
426✔
163
        ]);
426✔
164
    }
165

166
    /**
167
     * Finds the end of the right-hand side of the comparison at the given
168
     * index.
169
     *
170
     * The right-hand side ends when an operator with a lower precedence is
171
     * encountered or when the block level for `()`, `{}` or `[]` goes below
172
     * zero.
173
     *
174
     * @param Tokens $tokens The token list
175
     * @param int    $index  The index of the comparison
176
     *
177
     * @return int The last index of the right-hand side of the comparison
178
     */
179
    private function findComparisonEnd(Tokens $tokens, int $index): int
180
    {
181
        ++$index;
403✔
182
        $count = \count($tokens);
403✔
183

184
        while ($index < $count) {
403✔
185
            $token = $tokens[$index];
403✔
186

187
            if ($token->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) {
403✔
188
                ++$index;
401✔
189

190
                continue;
401✔
191
            }
192

193
            if ($this->isOfLowerPrecedence($token)) {
403✔
194
                break;
378✔
195
            }
196

197
            $block = Tokens::detectBlockType($token);
403✔
198

199
            if (null === $block) {
403✔
200
                ++$index;
391✔
201

202
                continue;
391✔
203
            }
204

205
            if (!$block['isStart']) {
147✔
206
                break;
20✔
207
            }
208

209
            $index = $tokens->findBlockEnd($block['type'], $index) + 1;
135✔
210
        }
211

212
        $prev = $tokens->getPrevMeaningfulToken($index);
403✔
213

214
        return $tokens[$prev]->isGivenKind(\T_CLOSE_TAG) ? $tokens->getPrevMeaningfulToken($prev) : $prev;
403✔
215
    }
216

217
    /**
218
     * Finds the start of the left-hand side of the comparison at the given
219
     * index.
220
     *
221
     * The left-hand side ends when an operator with a lower precedence is
222
     * encountered or when the block level for `()`, `{}` or `[]` goes below
223
     * zero.
224
     *
225
     * @param Tokens $tokens The token list
226
     * @param int    $index  The index of the comparison
227
     *
228
     * @return int The first index of the left-hand side of the comparison
229
     */
230
    private function findComparisonStart(Tokens $tokens, int $index): int
231
    {
232
        --$index;
381✔
233
        $nonBlockFound = false;
381✔
234

235
        while (0 <= $index) {
381✔
236
            $token = $tokens[$index];
381✔
237

238
            if ($token->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) {
381✔
239
                --$index;
379✔
240

241
                continue;
379✔
242
            }
243

244
            if ($token->isGivenKind(CT::T_NAMED_ARGUMENT_COLON)) {
381✔
245
                break;
1✔
246
            }
247

248
            if ($this->isOfLowerPrecedence($token)) {
381✔
249
                break;
359✔
250
            }
251

252
            $block = Tokens::detectBlockType($token);
381✔
253

254
            if (null === $block) {
381✔
255
                --$index;
373✔
256
                $nonBlockFound = true;
373✔
257

258
                continue;
373✔
259
            }
260

261
            if (
262
                $block['isStart']
135✔
263
                || ($nonBlockFound && Tokens::BLOCK_TYPE_CURLY_BRACE === $block['type']) // closing of structure not related to the comparison
135✔
264
            ) {
265
                break;
32✔
266
            }
267

268
            $index = $tokens->findBlockStart($block['type'], $index) - 1;
113✔
269
        }
270

271
        return $tokens->getNextMeaningfulToken($index);
381✔
272
    }
273

274
    private function fixTokens(Tokens $tokens): Tokens
275
    {
276
        for ($i = \count($tokens) - 1; $i > 1; --$i) {
403✔
277
            if ($tokens[$i]->isGivenKind($this->candidateTypes)) {
403✔
278
                $yoda = $this->candidateTypesConfiguration[$tokens[$i]->getId()];
399✔
279
            } elseif (
280
                ($tokens[$i]->equals('<') && \in_array('<', $this->candidateTypes, true))
403✔
281
                || ($tokens[$i]->equals('>') && \in_array('>', $this->candidateTypes, true))
403✔
282
            ) {
283
                $yoda = $this->candidateTypesConfiguration[$tokens[$i]->getContent()];
5✔
284
            } else {
285
                continue;
403✔
286
            }
287

288
            $fixableCompareInfo = $this->getCompareFixableInfo($tokens, $i, $yoda);
403✔
289

290
            if (null === $fixableCompareInfo) {
403✔
291
                continue;
402✔
292
            }
293

294
            $i = $this->fixTokensCompare(
274✔
295
                $tokens,
274✔
296
                $fixableCompareInfo['left']['start'],
274✔
297
                $fixableCompareInfo['left']['end'],
274✔
298
                $i,
274✔
299
                $fixableCompareInfo['right']['start'],
274✔
300
                $fixableCompareInfo['right']['end']
274✔
301
            );
274✔
302
        }
303

304
        return $tokens;
403✔
305
    }
306

307
    /**
308
     * Fixes the comparison at the given index.
309
     *
310
     * A comparison is considered fixed when
311
     * - both sides are a variable (e.g. $a === $b)
312
     * - neither side is a variable (e.g. self::CONST === 3)
313
     * - only the right-hand side is a variable (e.g. 3 === self::$var)
314
     *
315
     * If the left-hand side and right-hand side of the given comparison are
316
     * swapped, this function runs recursively on the previous left-hand-side.
317
     *
318
     * @return int an upper bound for all non-fixed comparisons
319
     */
320
    private function fixTokensCompare(
321
        Tokens $tokens,
322
        int $startLeft,
323
        int $endLeft,
324
        int $compareOperatorIndex,
325
        int $startRight,
326
        int $endRight
327
    ): int {
328
        $type = $tokens[$compareOperatorIndex]->getId();
274✔
329
        $content = $tokens[$compareOperatorIndex]->getContent();
274✔
330

331
        if (\array_key_exists($type, $this->candidatesMap)) {
274✔
332
            $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$type];
2✔
333
        } elseif (\array_key_exists($content, $this->candidatesMap)) {
272✔
334
            $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$content];
4✔
335
        }
336

337
        $right = $this->fixTokensComparePart($tokens, $startRight, $endRight);
274✔
338
        $left = $this->fixTokensComparePart($tokens, $startLeft, $endLeft);
274✔
339

340
        for ($i = $startRight; $i <= $endRight; ++$i) {
274✔
341
            $tokens->clearAt($i);
274✔
342
        }
343

344
        for ($i = $startLeft; $i <= $endLeft; ++$i) {
274✔
345
            $tokens->clearAt($i);
274✔
346
        }
347

348
        $tokens->insertAt($startRight, $left);
274✔
349
        $tokens->insertAt($startLeft, $right);
274✔
350

351
        return $startLeft;
274✔
352
    }
353

354
    private function fixTokensComparePart(Tokens $tokens, int $start, int $end): Tokens
355
    {
356
        $newTokens = $tokens->generatePartialCode($start, $end);
274✔
357
        $newTokens = $this->fixTokens(Tokens::fromCode(\sprintf('<?php %s;', $newTokens)));
274✔
358
        $newTokens->clearAt(\count($newTokens) - 1);
274✔
359
        $newTokens->clearAt(0);
274✔
360
        $newTokens->clearEmptyTokens();
274✔
361

362
        return $newTokens;
274✔
363
    }
364

365
    /**
366
     * @return null|array{left: array{start: int, end: int}, right: array{start: int, end: int}}
367
     */
368
    private function getCompareFixableInfo(Tokens $tokens, int $index, bool $yoda): ?array
369
    {
370
        $right = $this->getRightSideCompareFixableInfo($tokens, $index);
403✔
371

372
        if (!$yoda && $this->isOfLowerPrecedenceAssignment($tokens[$tokens->getNextMeaningfulToken($right['end'])])) {
403✔
373
            return null;
22✔
374
        }
375

376
        $left = $this->getLeftSideCompareFixableInfo($tokens, $index);
381✔
377

378
        if ($this->isListStatement($tokens, $left['start'], $left['end']) || $this->isListStatement($tokens, $right['start'], $right['end'])) {
381✔
379
            return null; // do not fix lists assignment inside statements
6✔
380
        }
381

382
        /** @var bool $strict */
383
        $strict = $this->configuration['always_move_variable'];
375✔
384
        $leftSideIsVariable = $this->isVariable($tokens, $left['start'], $left['end'], $strict);
375✔
385
        $rightSideIsVariable = $this->isVariable($tokens, $right['start'], $right['end'], $strict);
375✔
386

387
        if (!($leftSideIsVariable xor $rightSideIsVariable)) {
375✔
388
            return null; // both are (not) variables, do not touch
85✔
389
        }
390

391
        if (!$strict) { // special handling for braces with not "always_move_variable"
294✔
392
            $leftSideIsVariable = $leftSideIsVariable && !$tokens[$left['start']]->equals('(');
239✔
393
            $rightSideIsVariable = $rightSideIsVariable && !$tokens[$right['start']]->equals('(');
239✔
394
        }
395

396
        return ($yoda && !$leftSideIsVariable) || (!$yoda && !$rightSideIsVariable)
294✔
397
            ? null
293✔
398
            : ['left' => $left, 'right' => $right];
294✔
399
    }
400

401
    /**
402
     * @return array{start: int, end: int}
403
     */
404
    private function getLeftSideCompareFixableInfo(Tokens $tokens, int $index): array
405
    {
406
        return [
381✔
407
            'start' => $this->findComparisonStart($tokens, $index),
381✔
408
            'end' => $tokens->getPrevMeaningfulToken($index),
381✔
409
        ];
381✔
410
    }
411

412
    /**
413
     * @return array{start: int, end: int}
414
     */
415
    private function getRightSideCompareFixableInfo(Tokens $tokens, int $index): array
416
    {
417
        return [
403✔
418
            'start' => $tokens->getNextMeaningfulToken($index),
403✔
419
            'end' => $this->findComparisonEnd($tokens, $index),
403✔
420
        ];
403✔
421
    }
422

423
    private function isListStatement(Tokens $tokens, int $index, int $end): bool
424
    {
425
        for ($i = $index; $i <= $end; ++$i) {
381✔
426
            if ($tokens[$i]->isGivenKind([\T_LIST, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE])) {
381✔
427
                return true;
6✔
428
            }
429
        }
430

431
        return false;
381✔
432
    }
433

434
    /**
435
     * Checks whether the given token has a lower precedence than `T_IS_EQUAL`
436
     * or `T_IS_IDENTICAL`.
437
     *
438
     * @param Token $token The token to check
439
     *
440
     * @return bool Whether the token has a lower precedence
441
     */
442
    private function isOfLowerPrecedence(Token $token): bool
443
    {
444
        return $this->isOfLowerPrecedenceAssignment($token)
403✔
445
            || $token->isGivenKind([
403✔
446
                \T_BOOLEAN_AND,  // &&
403✔
447
                \T_BOOLEAN_OR,   // ||
403✔
448
                \T_CASE,         // case
403✔
449
                \T_DOUBLE_ARROW, // =>
403✔
450
                \T_ECHO,         // echo
403✔
451
                \T_GOTO,         // goto
403✔
452
                \T_LOGICAL_AND,  // and
403✔
453
                \T_LOGICAL_OR,   // or
403✔
454
                \T_LOGICAL_XOR,  // xor
403✔
455
                \T_OPEN_TAG,     // <?php
403✔
456
                \T_OPEN_TAG_WITH_ECHO,
403✔
457
                \T_PRINT,        // print
403✔
458
                \T_RETURN,       // return
403✔
459
                \T_THROW,        // throw
403✔
460
                \T_COALESCE,
403✔
461
                \T_YIELD,        // yield
403✔
462
                \T_YIELD_FROM,
403✔
463
                \T_REQUIRE,
403✔
464
                \T_REQUIRE_ONCE,
403✔
465
                \T_INCLUDE,
403✔
466
                \T_INCLUDE_ONCE,
403✔
467
            ])
403✔
468
            || $token->equalsAny([
403✔
469
                // bitwise and, or, xor
470
                '&', '|', '^',
403✔
471
                // ternary operators
472
                '?', ':',
403✔
473
                // end of PHP statement
474
                ',', ';',
403✔
475
            ]);
403✔
476
    }
477

478
    /**
479
     * Checks whether the given assignment token has a lower precedence than `T_IS_EQUAL`
480
     * or `T_IS_IDENTICAL`.
481
     */
482
    private function isOfLowerPrecedenceAssignment(Token $token): bool
483
    {
484
        return $token->equals('=') || $token->isGivenKind([
403✔
485
            \T_AND_EQUAL,      // &=
403✔
486
            \T_CONCAT_EQUAL,   // .=
403✔
487
            \T_DIV_EQUAL,      // /=
403✔
488
            \T_MINUS_EQUAL,    // -=
403✔
489
            \T_MOD_EQUAL,      // %=
403✔
490
            \T_MUL_EQUAL,      // *=
403✔
491
            \T_OR_EQUAL,       // |=
403✔
492
            \T_PLUS_EQUAL,     // +=
403✔
493
            \T_POW_EQUAL,      // **=
403✔
494
            \T_SL_EQUAL,       // <<=
403✔
495
            \T_SR_EQUAL,       // >>=
403✔
496
            \T_XOR_EQUAL,      // ^=
403✔
497
            \T_COALESCE_EQUAL, // ??=
403✔
498
        ]);
403✔
499
    }
500

501
    /**
502
     * Checks whether the tokens between the given start and end describe a
503
     * variable.
504
     *
505
     * @param Tokens $tokens The token list
506
     * @param int    $start  The first index of the possible variable
507
     * @param int    $end    The last index of the possible variable
508
     * @param bool   $strict Enable strict variable detection
509
     *
510
     * @return bool Whether the tokens describe a variable
511
     */
512
    private function isVariable(Tokens $tokens, int $start, int $end, bool $strict): bool
513
    {
514
        $tokenAnalyzer = new TokensAnalyzer($tokens);
375✔
515

516
        if ($start === $end) {
375✔
517
            return $tokens[$start]->isGivenKind(\T_VARIABLE);
357✔
518
        }
519

520
        if ($tokens[$start]->equals('(')) {
252✔
521
            return true;
26✔
522
        }
523

524
        if ($strict) {
230✔
525
            for ($index = $start; $index <= $end; ++$index) {
54✔
526
                if (
527
                    $tokens[$index]->isCast()
54✔
528
                    || $tokens[$index]->isGivenKind(\T_INSTANCEOF)
54✔
529
                    || $tokens[$index]->equals('!')
54✔
530
                    || $tokenAnalyzer->isBinaryOperator($index)
54✔
531
                ) {
532
                    return false;
46✔
533
                }
534
            }
535
        }
536

537
        $index = $start;
184✔
538

539
        // handle multiple braces around statement ((($a === 1)))
540
        while (
541
            $tokens[$index]->equals('(')
184✔
542
            && $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index) === $end
184✔
543
        ) {
544
            $index = $tokens->getNextMeaningfulToken($index);
×
545
            $end = $tokens->getPrevMeaningfulToken($end);
×
546
        }
547

548
        $expectString = false;
184✔
549

550
        while ($index <= $end) {
184✔
551
            $current = $tokens[$index];
184✔
552
            if ($current->isComment() || $current->isWhitespace() || $tokens->isEmptyAt($index)) {
184✔
553
                ++$index;
×
554

555
                continue;
×
556
            }
557

558
            // check if this is the last token
559
            if ($index === $end) {
184✔
560
                return $current->isGivenKind($expectString ? \T_STRING : \T_VARIABLE);
26✔
561
            }
562

563
            if ($current->isGivenKind([\T_LIST, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE])) {
184✔
564
                return false;
×
565
            }
566

567
            $nextIndex = $tokens->getNextMeaningfulToken($index);
184✔
568
            $next = $tokens[$nextIndex];
184✔
569

570
            // self:: or ClassName::
571
            if ($current->isGivenKind(\T_STRING) && $next->isGivenKind(\T_DOUBLE_COLON)) {
184✔
572
                $index = $tokens->getNextMeaningfulToken($nextIndex);
8✔
573

574
                continue;
8✔
575
            }
576

577
            // \ClassName
578
            if ($current->isGivenKind(\T_NS_SEPARATOR) && $next->isGivenKind(\T_STRING)) {
178✔
579
                $index = $nextIndex;
2✔
580

581
                continue;
2✔
582
            }
583

584
            // ClassName\
585
            if ($current->isGivenKind(\T_STRING) && $next->isGivenKind(\T_NS_SEPARATOR)) {
178✔
586
                $index = $nextIndex;
2✔
587

588
                continue;
2✔
589
            }
590

591
            // $a-> or a-> (as in $b->a->c)
592
            if ($current->isGivenKind([\T_STRING, \T_VARIABLE]) && $next->isObjectOperator()) {
176✔
593
                $index = $tokens->getNextMeaningfulToken($nextIndex);
36✔
594
                $expectString = true;
36✔
595

596
                continue;
36✔
597
            }
598

599
            // $a[...], a[...] (as in $c->a[$b]), $a{...} or a{...} (as in $c->a{$b})
600
            if (
601
                $current->isGivenKind($expectString ? \T_STRING : \T_VARIABLE)
169✔
602
                && $next->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']])
169✔
603
            ) {
604
                $index = $tokens->findBlockEnd(
23✔
605
                    $next->equals('[') ? Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE : Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE,
23✔
606
                    $nextIndex
23✔
607
                );
23✔
608

609
                if ($index === $end) {
23✔
610
                    return true;
14✔
611
                }
612

613
                $index = $tokens->getNextMeaningfulToken($index);
11✔
614

615
                if (!$tokens[$index]->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']]) && !$tokens[$index]->isObjectOperator()) {
11✔
616
                    return false;
2✔
617
                }
618

619
                $index = $tokens->getNextMeaningfulToken($index);
9✔
620
                $expectString = true;
9✔
621

622
                continue;
9✔
623
            }
624

625
            // $a(...) or $a->b(...)
626
            if ($strict && $current->isGivenKind([\T_STRING, \T_VARIABLE]) && $next->equals('(')) {
150✔
627
                return false;
6✔
628
            }
629

630
            // {...} (as in $a->{$b})
631
            if ($expectString && $current->isGivenKind(CT::T_DYNAMIC_PROP_BRACE_OPEN)) {
144✔
632
                $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, $index);
11✔
633
                if ($index === $end) {
11✔
634
                    return true;
2✔
635
                }
636

637
                $index = $tokens->getNextMeaningfulToken($index);
9✔
638

639
                if (!$tokens[$index]->isObjectOperator()) {
9✔
640
                    return false;
3✔
641
                }
642

643
                $index = $tokens->getNextMeaningfulToken($index);
6✔
644
                $expectString = true;
6✔
645

646
                continue;
6✔
647
            }
648

649
            break;
133✔
650
        }
651

652
        return !$this->isConstant($tokens, $start, $end);
133✔
653
    }
654

655
    private function isConstant(Tokens $tokens, int $index, int $end): bool
656
    {
657
        $expectArrayOnly = false;
133✔
658
        $expectNumberOnly = false;
133✔
659
        $expectNothing = false;
133✔
660

661
        for (; $index <= $end; ++$index) {
133✔
662
            $token = $tokens[$index];
133✔
663

664
            if ($token->isComment() || $token->isWhitespace()) {
133✔
665
                continue;
14✔
666
            }
667

668
            if ($expectNothing) {
133✔
669
                return false;
10✔
670
            }
671

672
            if ($expectArrayOnly) {
133✔
673
                if ($token->equalsAny(['(', ')', [CT::T_ARRAY_SQUARE_BRACE_CLOSE]])) {
38✔
674
                    continue;
32✔
675
                }
676

677
                return false;
30✔
678
            }
679

680
            if ($token->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
133✔
681
                $expectArrayOnly = true;
38✔
682

683
                continue;
38✔
684
            }
685

686
            if ($expectNumberOnly && !$token->isGivenKind([\T_LNUMBER, \T_DNUMBER])) {
97✔
687
                return false;
×
688
            }
689

690
            if ($token->equals('-')) {
97✔
691
                $expectNumberOnly = true;
6✔
692

693
                continue;
6✔
694
            }
695

696
            if (
697
                $token->isGivenKind([\T_LNUMBER, \T_DNUMBER, \T_CONSTANT_ENCAPSED_STRING])
97✔
698
                || $token->equalsAny([[\T_STRING, 'true'], [\T_STRING, 'false'], [\T_STRING, 'null']])
97✔
699
            ) {
700
                $expectNothing = true;
16✔
701

702
                continue;
16✔
703
            }
704

705
            return false;
87✔
706
        }
707

708
        return true;
14✔
709
    }
710

711
    private function resolveConfiguration(): void
712
    {
713
        $candidateTypes = [];
426✔
714
        $this->candidatesMap = [];
426✔
715

716
        if (null !== $this->configuration['equal']) {
426✔
717
            // `==`, `!=` and `<>`
718
            $candidateTypes[\T_IS_EQUAL] = $this->configuration['equal'];
426✔
719
            $candidateTypes[\T_IS_NOT_EQUAL] = $this->configuration['equal'];
426✔
720
        }
721

722
        if (null !== $this->configuration['identical']) {
426✔
723
            // `===` and `!==`
724
            $candidateTypes[\T_IS_IDENTICAL] = $this->configuration['identical'];
426✔
725
            $candidateTypes[\T_IS_NOT_IDENTICAL] = $this->configuration['identical'];
426✔
726
        }
727

728
        if (null !== $this->configuration['less_and_greater']) {
426✔
729
            // `<`, `<=`, `>` and `>=`
730
            $candidateTypes[\T_IS_SMALLER_OR_EQUAL] = $this->configuration['less_and_greater'];
10✔
731
            $this->candidatesMap[\T_IS_SMALLER_OR_EQUAL] = new Token([\T_IS_GREATER_OR_EQUAL, '>=']);
10✔
732

733
            $candidateTypes[\T_IS_GREATER_OR_EQUAL] = $this->configuration['less_and_greater'];
10✔
734
            $this->candidatesMap[\T_IS_GREATER_OR_EQUAL] = new Token([\T_IS_SMALLER_OR_EQUAL, '<=']);
10✔
735

736
            $candidateTypes['<'] = $this->configuration['less_and_greater'];
10✔
737
            $this->candidatesMap['<'] = new Token('>');
10✔
738

739
            $candidateTypes['>'] = $this->configuration['less_and_greater'];
10✔
740
            $this->candidatesMap['>'] = new Token('<');
10✔
741
        }
742

743
        $this->candidateTypesConfiguration = $candidateTypes;
426✔
744
        $this->candidateTypes = array_keys($candidateTypes);
426✔
745
    }
746
}
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