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

keradus / PHP-CS-Fixer / 17279562118

27 Aug 2025 09:47PM UTC coverage: 94.693%. Remained the same
17279562118

push

github

keradus
CS

28316 of 29903 relevant lines covered (94.69%)

45.61 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
 * @phpstan-import-type _PhpTokenKind from Token
48
 *
49
 * @author Bram Gotink <bram@gotink.me>
50
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
51
 *
52
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise.
53
 */
54
final class YodaStyleFixer extends AbstractFixer implements ConfigurableFixerInterface
55
{
56
    /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
57
    use ConfigurableFixerTrait;
58

59
    /**
60
     * @var array<_PhpTokenKind, Token>
61
     */
62
    private array $candidatesMap;
63

64
    /**
65
     * @var array<_PhpTokenKind, null|bool>
66
     */
67
    private array $candidateTypesConfiguration;
68

69
    /**
70
     * @var list<_PhpTokenKind>
71
     */
72
    private array $candidateTypes;
73

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

123
    /**
124
     * {@inheritdoc}
125
     *
126
     * Must run after IsNullFixer.
127
     */
128
    public function getPriority(): int
129
    {
130
        return 0;
1✔
131
    }
132

133
    public function isCandidate(Tokens $tokens): bool
134
    {
135
        return $tokens->isAnyTokenKindsFound($this->candidateTypes);
415✔
136
    }
137

138
    protected function configurePostNormalisation(): void
139
    {
140
        $this->resolveConfiguration();
426✔
141
    }
142

143
    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
144
    {
145
        $this->fixTokens($tokens);
403✔
146
    }
147

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

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

188
        while ($index < $count) {
403✔
189
            $token = $tokens[$index];
403✔
190

191
            if ($token->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) {
403✔
192
                ++$index;
401✔
193

194
                continue;
401✔
195
            }
196

197
            if ($this->isOfLowerPrecedence($token)) {
403✔
198
                break;
378✔
199
            }
200

201
            $block = Tokens::detectBlockType($token);
403✔
202

203
            if (null === $block) {
403✔
204
                ++$index;
391✔
205

206
                continue;
391✔
207
            }
208

209
            if (!$block['isStart']) {
147✔
210
                break;
20✔
211
            }
212

213
            $index = $tokens->findBlockEnd($block['type'], $index) + 1;
135✔
214
        }
215

216
        $prev = $tokens->getPrevMeaningfulToken($index);
403✔
217

218
        return $tokens[$prev]->isGivenKind(\T_CLOSE_TAG) ? $tokens->getPrevMeaningfulToken($prev) : $prev;
403✔
219
    }
220

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

239
        while (0 <= $index) {
381✔
240
            $token = $tokens[$index];
381✔
241

242
            if ($token->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) {
381✔
243
                --$index;
379✔
244

245
                continue;
379✔
246
            }
247

248
            if ($token->isGivenKind(CT::T_NAMED_ARGUMENT_COLON)) {
381✔
249
                break;
1✔
250
            }
251

252
            if ($this->isOfLowerPrecedence($token)) {
381✔
253
                break;
359✔
254
            }
255

256
            $block = Tokens::detectBlockType($token);
381✔
257

258
            if (null === $block) {
381✔
259
                --$index;
373✔
260
                $nonBlockFound = true;
373✔
261

262
                continue;
373✔
263
            }
264

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

272
            $index = $tokens->findBlockStart($block['type'], $index) - 1;
113✔
273
        }
274

275
        return $tokens->getNextMeaningfulToken($index);
381✔
276
    }
277

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

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

294
            if (null === $fixableCompareInfo) {
403✔
295
                continue;
402✔
296
            }
297

298
            $i = $this->fixTokensCompare(
274✔
299
                $tokens,
274✔
300
                $fixableCompareInfo['left']['start'],
274✔
301
                $fixableCompareInfo['left']['end'],
274✔
302
                $i,
274✔
303
                $fixableCompareInfo['right']['start'],
274✔
304
                $fixableCompareInfo['right']['end']
274✔
305
            );
274✔
306
        }
307

308
        return $tokens;
403✔
309
    }
310

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

335
        if (\array_key_exists($type, $this->candidatesMap)) {
274✔
336
            $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$type];
2✔
337
        } elseif (\array_key_exists($content, $this->candidatesMap)) {
272✔
338
            $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$content];
4✔
339
        }
340

341
        $right = $this->fixTokensComparePart($tokens, $startRight, $endRight);
274✔
342
        $left = $this->fixTokensComparePart($tokens, $startLeft, $endLeft);
274✔
343

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

348
        for ($i = $startLeft; $i <= $endLeft; ++$i) {
274✔
349
            $tokens->clearAt($i);
274✔
350
        }
351

352
        $tokens->insertAt($startRight, $left);
274✔
353
        $tokens->insertAt($startLeft, $right);
274✔
354

355
        return $startLeft;
274✔
356
    }
357

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

366
        return $newTokens;
274✔
367
    }
368

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

376
        if (!$yoda && $this->isOfLowerPrecedenceAssignment($tokens[$tokens->getNextMeaningfulToken($right['end'])])) {
403✔
377
            return null;
22✔
378
        }
379

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

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

386
        /** @var bool $strict */
387
        $strict = $this->configuration['always_move_variable'];
375✔
388
        $leftSideIsVariable = $this->isVariable($tokens, $left['start'], $left['end'], $strict);
375✔
389
        $rightSideIsVariable = $this->isVariable($tokens, $right['start'], $right['end'], $strict);
375✔
390

391
        if (!($leftSideIsVariable xor $rightSideIsVariable)) {
375✔
392
            return null; // both are (not) variables, do not touch
85✔
393
        }
394

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

400
        return ($yoda && !$leftSideIsVariable) || (!$yoda && !$rightSideIsVariable)
294✔
401
            ? null
293✔
402
            : ['left' => $left, 'right' => $right];
294✔
403
    }
404

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

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

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

435
        return false;
381✔
436
    }
437

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

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

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

520
        if ($start === $end) {
375✔
521
            return $tokens[$start]->isGivenKind(\T_VARIABLE);
357✔
522
        }
523

524
        if ($tokens[$start]->equals('(')) {
252✔
525
            return true;
26✔
526
        }
527

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

541
        $index = $start;
184✔
542

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

552
        $expectString = false;
184✔
553

554
        while ($index <= $end) {
184✔
555
            $current = $tokens[$index];
184✔
556
            if ($current->isComment() || $current->isWhitespace() || $tokens->isEmptyAt($index)) {
184✔
557
                ++$index;
×
558

559
                continue;
×
560
            }
561

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

567
            if ($current->isGivenKind([\T_LIST, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE])) {
184✔
568
                return false;
×
569
            }
570

571
            $nextIndex = $tokens->getNextMeaningfulToken($index);
184✔
572
            $next = $tokens[$nextIndex];
184✔
573

574
            // self:: or ClassName::
575
            if ($current->isGivenKind(\T_STRING) && $next->isGivenKind(\T_DOUBLE_COLON)) {
184✔
576
                $index = $tokens->getNextMeaningfulToken($nextIndex);
8✔
577

578
                continue;
8✔
579
            }
580

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

585
                continue;
2✔
586
            }
587

588
            // ClassName\
589
            if ($current->isGivenKind(\T_STRING) && $next->isGivenKind(\T_NS_SEPARATOR)) {
178✔
590
                $index = $nextIndex;
2✔
591

592
                continue;
2✔
593
            }
594

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

600
                continue;
36✔
601
            }
602

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

613
                if ($index === $end) {
23✔
614
                    return true;
14✔
615
                }
616

617
                $index = $tokens->getNextMeaningfulToken($index);
11✔
618

619
                if (!$tokens[$index]->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']]) && !$tokens[$index]->isObjectOperator()) {
11✔
620
                    return false;
2✔
621
                }
622

623
                $index = $tokens->getNextMeaningfulToken($index);
9✔
624
                $expectString = true;
9✔
625

626
                continue;
9✔
627
            }
628

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

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

641
                $index = $tokens->getNextMeaningfulToken($index);
9✔
642

643
                if (!$tokens[$index]->isObjectOperator()) {
9✔
644
                    return false;
3✔
645
                }
646

647
                $index = $tokens->getNextMeaningfulToken($index);
6✔
648
                $expectString = true;
6✔
649

650
                continue;
6✔
651
            }
652

653
            break;
133✔
654
        }
655

656
        return !$this->isConstant($tokens, $start, $end);
133✔
657
    }
658

659
    private function isConstant(Tokens $tokens, int $index, int $end): bool
660
    {
661
        $expectArrayOnly = false;
133✔
662
        $expectNumberOnly = false;
133✔
663
        $expectNothing = false;
133✔
664

665
        for (; $index <= $end; ++$index) {
133✔
666
            $token = $tokens[$index];
133✔
667

668
            if ($token->isComment() || $token->isWhitespace()) {
133✔
669
                continue;
14✔
670
            }
671

672
            if ($expectNothing) {
133✔
673
                return false;
10✔
674
            }
675

676
            if ($expectArrayOnly) {
133✔
677
                if ($token->equalsAny(['(', ')', [CT::T_ARRAY_SQUARE_BRACE_CLOSE]])) {
38✔
678
                    continue;
32✔
679
                }
680

681
                return false;
30✔
682
            }
683

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

687
                continue;
38✔
688
            }
689

690
            if ($expectNumberOnly && !$token->isGivenKind([\T_LNUMBER, \T_DNUMBER])) {
97✔
691
                return false;
×
692
            }
693

694
            if ($token->equals('-')) {
97✔
695
                $expectNumberOnly = true;
6✔
696

697
                continue;
6✔
698
            }
699

700
            if (
701
                $token->isGivenKind([\T_LNUMBER, \T_DNUMBER, \T_CONSTANT_ENCAPSED_STRING])
97✔
702
                || $token->equalsAny([[\T_STRING, 'true'], [\T_STRING, 'false'], [\T_STRING, 'null']])
97✔
703
            ) {
704
                $expectNothing = true;
16✔
705

706
                continue;
16✔
707
            }
708

709
            return false;
87✔
710
        }
711

712
        return true;
14✔
713
    }
714

715
    private function resolveConfiguration(): void
716
    {
717
        $candidateTypes = [];
426✔
718
        $this->candidatesMap = [];
426✔
719

720
        if (null !== $this->configuration['equal']) {
426✔
721
            // `==`, `!=` and `<>`
722
            $candidateTypes[\T_IS_EQUAL] = $this->configuration['equal'];
426✔
723
            $candidateTypes[\T_IS_NOT_EQUAL] = $this->configuration['equal'];
426✔
724
        }
725

726
        if (null !== $this->configuration['identical']) {
426✔
727
            // `===` and `!==`
728
            $candidateTypes[\T_IS_IDENTICAL] = $this->configuration['identical'];
426✔
729
            $candidateTypes[\T_IS_NOT_IDENTICAL] = $this->configuration['identical'];
426✔
730
        }
731

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

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

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

743
            $candidateTypes['>'] = $this->configuration['less_and_greater'];
10✔
744
            $this->candidatesMap['>'] = new Token('<');
10✔
745
        }
746

747
        $this->candidateTypesConfiguration = $candidateTypes;
426✔
748
        $this->candidateTypes = array_keys($candidateTypes);
426✔
749
    }
750
}
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