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

keradus / PHP-CS-Fixer / 16018263876

02 Jul 2025 06:58AM UTC coverage: 94.846% (-0.002%) from 94.848%
16018263876

push

github

keradus
debug2

28193 of 29725 relevant lines covered (94.85%)

45.34 hits per line

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

94.37
/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.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\ClassNotation;
16

17
use PhpCsFixer\AbstractFixer;
18
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
19
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
20
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
21
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
22
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
23
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
24
use PhpCsFixer\FixerDefinition\CodeSample;
25
use PhpCsFixer\FixerDefinition\FixerDefinition;
26
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
27
use PhpCsFixer\FixerDefinition\VersionSpecification;
28
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
29
use PhpCsFixer\Preg;
30
use PhpCsFixer\Tokenizer\CT;
31
use PhpCsFixer\Tokenizer\FCT;
32
use PhpCsFixer\Tokenizer\Token;
33
use PhpCsFixer\Tokenizer\Tokens;
34
use PhpCsFixer\Tokenizer\TokensAnalyzer;
35
use PhpCsFixer\Utils;
36
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
37

38
/**
39
 * Make sure there is one blank line above and below class elements.
40
 *
41
 * The exception is when an element is the first or last item in a 'classy'.
42
 *
43
 * @phpstan-type _Class array{
44
 *      index: int,
45
 *      open: int,
46
 *      close: int,
47
 *      elements: non-empty-list<_Element>
48
 *  }
49
 * @phpstan-type _Element array{token: Token, type: string, index: int, start?: int, end?: int}
50
 *
51
 * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
52
 *
53
 * @phpstan-type _AutogeneratedInputConfiguration array{
54
 *  elements?: array<string, string>,
55
 * }
56
 * @phpstan-type _AutogeneratedComputedConfiguration array{
57
 *  elements: array<string, string>,
58
 * }
59
 */
60
final class ClassAttributesSeparationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
61
{
62
    /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
63
    use ConfigurableFixerTrait;
64

65
    /**
66
     * @internal
67
     */
68
    public const SPACING_NONE = 'none';
69

70
    /**
71
     * @internal
72
     */
73
    public const SPACING_ONE = 'one';
74

75
    private const SPACING_ONLY_IF_META = 'only_if_meta';
76
    private const MODIFIER_TYPES = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_ABSTRACT, T_FINAL, T_STATIC, T_STRING, T_NS_SEPARATOR, T_VAR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET];
77

78
    /**
79
     * @var array<string, string>
80
     */
81
    private array $classElementTypes = [];
82

83
    public function getDefinition(): FixerDefinitionInterface
84
    {
85
        return new FixerDefinition(
3✔
86
            'Class, trait and interface elements must be separated with one or none blank line.',
3✔
87
            [
3✔
88
                new CodeSample(
3✔
89
                    '<?php
3✔
90
final class Sample
91
{
92
    protected function foo()
93
    {
94
    }
95
    protected function bar()
96
    {
97
    }
98

99

100
}
101
'
3✔
102
                ),
3✔
103
                new CodeSample(
3✔
104
                    '<?php
3✔
105
class Sample
106
{private $a; // foo
107
    /** second in a hour */
108
    private $b;
109
}
110
',
3✔
111
                    ['elements' => ['property' => self::SPACING_ONE]]
3✔
112
                ),
3✔
113
                new CodeSample(
3✔
114
                    '<?php
3✔
115
class Sample
116
{
117
    const A = 1;
118
    /** seconds in some hours */
119
    const B = 3600;
120
}
121
',
3✔
122
                    ['elements' => ['const' => self::SPACING_ONE]]
3✔
123
                ),
3✔
124
                new CodeSample(
3✔
125
                    '<?php
3✔
126
class Sample
127
{
128
    /** @var int */
129
    const SECOND = 1;
130
    /** @var int */
131
    const MINUTE = 60;
132

133
    const HOUR = 3600;
134

135
    const DAY = 86400;
136
}
137
',
3✔
138
                    ['elements' => ['const' => self::SPACING_ONLY_IF_META]]
3✔
139
                ),
3✔
140
                new VersionSpecificCodeSample(
3✔
141
                    '<?php
3✔
142
class Sample
143
{
144
    public $a;
145
    #[SetUp]
146
    public $b;
147
    /** @var string */
148
    public $c;
149
    /** @internal */
150
    #[Assert\String()]
151
    public $d;
152

153
    public $e;
154
}
155
',
3✔
156
                    new VersionSpecification(8_00_00),
3✔
157
                    ['elements' => ['property' => self::SPACING_ONLY_IF_META]]
3✔
158
                ),
3✔
159
            ]
3✔
160
        );
3✔
161
    }
162

163
    /**
164
     * {@inheritdoc}
165
     *
166
     * Must run before BracesFixer, IndentationTypeFixer, NoExtraBlankLinesFixer, StatementIndentationFixer.
167
     * Must run after OrderedClassElementsFixer, PhpUnitDataProviderMethodOrderFixer, SingleClassElementPerStatementFixer, VisibilityRequiredFixer.
168
     */
169
    public function getPriority(): int
170
    {
171
        return 55;
1✔
172
    }
173

174
    public function isCandidate(Tokens $tokens): bool
175
    {
176
        return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
94✔
177
    }
178

179
    protected function configurePostNormalisation(): void
180
    {
181
        $this->classElementTypes = []; // reset previous configuration
113✔
182

183
        foreach ($this->configuration['elements'] as $elementType => $spacing) {
113✔
184
            $this->classElementTypes[$elementType] = $spacing;
113✔
185
        }
186
    }
187

188
    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
189
    {
190
        foreach ($this->getElementsByClass($tokens) as $class) {
94✔
191
            $elements = $class['elements'];
92✔
192
            $elementCount = \count($elements);
92✔
193

194
            if (0 === $elementCount) {
92✔
195
                continue;
×
196
            }
197

198
            if (isset($this->classElementTypes[$elements[0]['type']])) {
92✔
199
                $this->fixSpaceBelowClassElement($tokens, $class);
88✔
200
                $this->fixSpaceAboveClassElement($tokens, $class, 0);
88✔
201
            }
202

203
            for ($index = 1; $index < $elementCount; ++$index) {
92✔
204
                if (isset($this->classElementTypes[$elements[$index]['type']])) {
64✔
205
                    $this->fixSpaceAboveClassElement($tokens, $class, $index);
63✔
206
                }
207
            }
208
        }
209
    }
210

211
    protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
212
    {
213
        return new FixerConfigurationResolver([
113✔
214
            (new FixerOptionBuilder('elements', 'Dictionary of `const|method|property|trait_import|case` => `none|one|only_if_meta` values.'))
113✔
215
                ->setAllowedTypes(['array<string, string>'])
113✔
216
                ->setAllowedValues([static function (array $option): bool {
113✔
217
                    foreach ($option as $type => $spacing) {
113✔
218
                        $supportedTypes = ['const', 'method', 'property', 'trait_import', 'case'];
113✔
219

220
                        if (!\in_array($type, $supportedTypes, true)) {
113✔
221
                            throw new InvalidOptionsException(
2✔
222
                                \sprintf(
2✔
223
                                    'Unexpected element type, expected any of %s, got "%s".',
2✔
224
                                    Utils::naturalLanguageJoin($supportedTypes),
2✔
225
                                    \gettype($type).'#'.$type
2✔
226
                                )
2✔
227
                            );
2✔
228
                        }
229

230
                        $supportedSpacings = [self::SPACING_NONE, self::SPACING_ONE, self::SPACING_ONLY_IF_META];
113✔
231

232
                        if (!\in_array($spacing, $supportedSpacings, true)) {
113✔
233
                            throw new InvalidOptionsException(
1✔
234
                                \sprintf(
1✔
235
                                    'Unexpected spacing for element type "%s", expected any of %s, got "%s".',
1✔
236
                                    $spacing,
1✔
237
                                    Utils::naturalLanguageJoin($supportedSpacings),
1✔
238
                                    \is_object($spacing) ? \get_class($spacing) : (null === $spacing ? 'null' : \gettype($spacing).'#'.$spacing)
1✔
239
                                )
1✔
240
                            );
1✔
241
                        }
242
                    }
243

244
                    return true;
113✔
245
                }])
113✔
246
                ->setDefault([
113✔
247
                    'const' => self::SPACING_ONE,
113✔
248
                    'method' => self::SPACING_ONE,
113✔
249
                    'property' => self::SPACING_ONE,
113✔
250
                    'trait_import' => self::SPACING_NONE,
113✔
251
                    'case' => self::SPACING_NONE,
113✔
252
                ])
113✔
253
                ->getOption(),
113✔
254
        ]);
113✔
255
    }
256

257
    /**
258
     * Fix spacing above an element of a class, interface or trait.
259
     *
260
     * Deals with comments, PHPDocs and spaces above the element with respect to the position of the
261
     * element within the class, interface or trait.
262
     *
263
     * @param _Class $class
264
     */
265
    private function fixSpaceAboveClassElement(Tokens $tokens, array $class, int $elementIndex): void
266
    {
267
        $element = $class['elements'][$elementIndex];
91✔
268
        $elementAboveEnd = isset($class['elements'][$elementIndex + 1]) ? $class['elements'][$elementIndex + 1]['end'] : 0;
91✔
269
        $nonWhiteAbove = $tokens->getPrevNonWhitespace($element['start']);
91✔
270

271
        // element is directly after class open brace
272
        if ($nonWhiteAbove === $class['open']) {
91✔
273
            $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1);
64✔
274

275
            return;
64✔
276
        }
277

278
        // deal with comments above an element
279
        if ($tokens[$nonWhiteAbove]->isGivenKind(T_COMMENT)) {
81✔
280
            // check if the comment belongs to the previous element
281
            if ($elementAboveEnd === $nonWhiteAbove) {
25✔
282
                $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex));
8✔
283

284
                return;
8✔
285
            }
286

287
            // more than one line break, always bring it back to 2 line breaks between the element start and what is above it
288
            if ($tokens[$nonWhiteAbove + 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 1) {
19✔
289
                $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2);
8✔
290

291
                return;
8✔
292
            }
293

294
            // there are 2 cases:
295
            if (
296
                1 === $element['start'] - $nonWhiteAbove
13✔
297
                || $tokens[$nonWhiteAbove - 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove - 1]->getContent(), "\n") > 0
13✔
298
                || $tokens[$nonWhiteAbove + 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 0
13✔
299
            ) {
300
                // 1. The comment is meant for the element (although not a PHPDoc),
301
                //    make sure there is one line break between the element and the comment...
302
                $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1);
13✔
303
                //    ... and make sure there is blank line above the comment (with the exception when it is directly after a class opening)
304
                $nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd);
13✔
305
                $nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove);
13✔
306

307
                if ($nonWhiteAboveComment === $class['open']) {
13✔
308
                    if ($tokens[$nonWhiteAboveComment - 1]->isWhitespace() && substr_count($tokens[$nonWhiteAboveComment - 1]->getContent(), "\n") > 0) {
10✔
309
                        $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, 1);
7✔
310
                    }
311
                } else {
312
                    $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, 2);
3✔
313
                }
314
            } else {
315
                // 2. The comment belongs to the code above the element,
316
                //    make sure there is a blank line above the element (i.e. 2 line breaks)
317
                $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2);
×
318
            }
319

320
            return;
13✔
321
        }
322

323
        // deal with element with a PHPDoc/attribute above it
324
        if ($tokens[$nonWhiteAbove]->isGivenKind([T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE])) {
64✔
325
            // there should be one linebreak between the element and the attribute above it
326
            $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1);
24✔
327

328
            // make sure there is blank line above the comment (with the exception when it is directly after a class opening)
329
            $nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd);
24✔
330
            $nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove);
24✔
331

332
            $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $class['open'] ? 1 : 2);
24✔
333

334
            return;
24✔
335
        }
336

337
        $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex));
54✔
338
    }
339

340
    /**
341
     * @param _Class $class
342
     */
343
    private function determineRequiredLineCount(Tokens $tokens, array $class, int $elementIndex): int
344
    {
345
        $type = $class['elements'][$elementIndex]['type'];
55✔
346
        $spacing = $this->classElementTypes[$type];
55✔
347

348
        if (self::SPACING_ONE === $spacing) {
55✔
349
            return 2;
40✔
350
        }
351

352
        if (self::SPACING_NONE === $spacing) {
21✔
353
            if (!isset($class['elements'][$elementIndex + 1])) {
14✔
354
                return 1;
×
355
            }
356

357
            $aboveElement = $class['elements'][$elementIndex + 1];
14✔
358

359
            if ($aboveElement['type'] !== $type) {
14✔
360
                return 2;
2✔
361
            }
362

363
            $aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($aboveElement['start']);
14✔
364

365
            return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1;
14✔
366
        }
367

368
        if (self::SPACING_ONLY_IF_META === $spacing) {
7✔
369
            $aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($class['elements'][$elementIndex]['start']);
7✔
370

371
            return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1;
7✔
372
        }
373

374
        throw new \RuntimeException(\sprintf('Unknown spacing "%s".', $spacing));
×
375
    }
376

377
    /**
378
     * @param _Class $class
379
     */
380
    private function fixSpaceBelowClassElement(Tokens $tokens, array $class): void
381
    {
382
        $element = $class['elements'][0];
88✔
383

384
        // if this is last element fix; fix to the class end `}` here if appropriate
385
        if ($class['close'] === $tokens->getNextNonWhitespace($element['end'])) {
88✔
386
            $this->correctLineBreaks($tokens, $element['end'], $class['close'], 1);
87✔
387
        }
388
    }
389

390
    private function correctLineBreaks(Tokens $tokens, int $startIndex, int $endIndex, int $reqLineCount): void
391
    {
392
        $lineEnding = $this->whitespacesConfig->getLineEnding();
91✔
393

394
        ++$startIndex;
91✔
395
        $numbOfWhiteTokens = $endIndex - $startIndex;
91✔
396

397
        if (0 === $numbOfWhiteTokens) {
91✔
398
            $tokens->insertAt($startIndex, new Token([T_WHITESPACE, str_repeat($lineEnding, $reqLineCount)]));
17✔
399

400
            return;
17✔
401
        }
402

403
        $lineBreakCount = $this->getLineBreakCount($tokens, $startIndex, $endIndex);
91✔
404

405
        if ($reqLineCount === $lineBreakCount) {
91✔
406
            return;
91✔
407
        }
408

409
        if ($lineBreakCount < $reqLineCount) {
69✔
410
            $tokens[$startIndex] = new Token([
50✔
411
                T_WHITESPACE,
50✔
412
                str_repeat($lineEnding, $reqLineCount - $lineBreakCount).$tokens[$startIndex]->getContent(),
50✔
413
            ]);
50✔
414

415
            return;
50✔
416
        }
417

418
        // $lineCount = > $reqLineCount : check the one Token case first since this one will be true most of the time
419
        if (1 === $numbOfWhiteTokens) {
39✔
420
            $tokens[$startIndex] = new Token([
39✔
421
                T_WHITESPACE,
39✔
422
                Preg::replace('/\r\n|\n/', '', $tokens[$startIndex]->getContent(), $lineBreakCount - $reqLineCount),
39✔
423
            ]);
39✔
424

425
            return;
39✔
426
        }
427

428
        // $numbOfWhiteTokens = > 1
429
        $toReplaceCount = $lineBreakCount - $reqLineCount;
×
430

431
        for ($i = $startIndex; $i < $endIndex && $toReplaceCount > 0; ++$i) {
×
432
            $tokenLineCount = substr_count($tokens[$i]->getContent(), "\n");
×
433

434
            if ($tokenLineCount > 0) {
×
435
                $tokens[$i] = new Token([
×
436
                    T_WHITESPACE,
×
437
                    Preg::replace('/\r\n|\n/', '', $tokens[$i]->getContent(), min($toReplaceCount, $tokenLineCount)),
×
438
                ]);
×
439
                $toReplaceCount -= $tokenLineCount;
×
440
            }
441
        }
442
    }
443

444
    private function getLineBreakCount(Tokens $tokens, int $startIndex, int $endIndex): int
445
    {
446
        $lineCount = 0;
99✔
447

448
        for ($i = $startIndex; $i < $endIndex; ++$i) {
99✔
449
            $lineCount += substr_count($tokens[$i]->getContent(), "\n");
99✔
450
        }
451

452
        return $lineCount;
99✔
453
    }
454

455
    private function findCommentBlockStart(Tokens $tokens, int $start, int $elementAboveEnd): int
456
    {
457
        for ($i = $start; $i > $elementAboveEnd; --$i) {
44✔
458
            if ($tokens[$i]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
44✔
459
                $start = $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $i);
7✔
460

461
                continue;
7✔
462
            }
463

464
            if ($tokens[$i]->isComment()) {
44✔
465
                $start = $i;
39✔
466

467
                continue;
39✔
468
            }
469

470
            if (!$tokens[$i]->isWhitespace() || $this->getLineBreakCount($tokens, $i, $i + 1) > 1) {
44✔
471
                break;
40✔
472
            }
473
        }
474

475
        return $start;
44✔
476
    }
477

478
    /**
479
     * @TODO Introduce proper DTO instead of an array
480
     *
481
     * @return \Generator<_Class>
482
     */
483
    private function getElementsByClass(Tokens $tokens): \Generator
484
    {
485
        $tokensAnalyzer = new TokensAnalyzer($tokens);
94✔
486
        $class = $classIndex = false;
94✔
487

488
        foreach (array_reverse($tokensAnalyzer->getClassyElements(), true) as $index => $element) {
94✔
489
            $element['index'] = $index;
92✔
490

491
            if ($element['classIndex'] !== $classIndex) {
92✔
492
                if (false !== $class) {
92✔
493
                    yield $class;
4✔
494
                }
495

496
                $classIndex = $element['classIndex'];
92✔
497
                $classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']);
92✔
498
                $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen);
92✔
499
                $class = [
92✔
500
                    'index' => $classIndex,
92✔
501
                    'open' => $classOpen,
92✔
502
                    'close' => $classEnd,
92✔
503
                    'elements' => [],
92✔
504
                ];
92✔
505
            }
506

507
            unset($element['classIndex']);
92✔
508
            $element['start'] = $this->getFirstTokenIndexOfClassElement($tokens, $class, $element);
92✔
509
            $element['end'] = $this->getLastTokenIndexOfClassElement($tokens, $class, $element, $tokensAnalyzer);
92✔
510

511
            $class['elements'][] = $element; // reset the key by design
92✔
512
        }
513

514
        if (false !== $class) {
94✔
515
            yield $class;
92✔
516
        }
517
    }
518

519
    /**
520
     * including trailing single line comments if belonging to the class element.
521
     *
522
     * @param _Class   $class
523
     * @param _Element $element
524
     */
525
    private function getFirstTokenIndexOfClassElement(Tokens $tokens, array $class, array $element): int
526
    {
527
        $firstElementAttributeIndex = $element['index'];
92✔
528

529
        do {
530
            $nonWhiteAbove = $tokens->getPrevMeaningfulToken($firstElementAttributeIndex);
92✔
531

532
            if (null !== $nonWhiteAbove && $tokens[$nonWhiteAbove]->isGivenKind(self::MODIFIER_TYPES)) {
92✔
533
                $firstElementAttributeIndex = $nonWhiteAbove;
77✔
534
            } else {
535
                break;
92✔
536
            }
537
        } while ($firstElementAttributeIndex > $class['open']);
77✔
538

539
        return $firstElementAttributeIndex;
92✔
540
    }
541

542
    /**
543
     * including trailing single line comments if belonging to the class element.
544
     *
545
     * @param _Class   $class
546
     * @param _Element $element
547
     */
548
    private function getLastTokenIndexOfClassElement(Tokens $tokens, array $class, array $element, TokensAnalyzer $tokensAnalyzer): int
549
    {
550
        // find last token of the element
551
        if ('method' === $element['type'] && !$tokens[$class['index']]->isGivenKind(T_INTERFACE)) {
92✔
552
            $attributes = $tokensAnalyzer->getMethodAttributes($element['index']);
53✔
553

554
            if (true === $attributes['abstract']) {
53✔
555
                $elementEndIndex = $tokens->getNextTokenOfKind($element['index'], [';']);
5✔
556
            } else {
557
                $elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($element['index'], ['{']));
51✔
558
            }
559
        } elseif ('trait_import' === $element['type']) {
62✔
560
            $elementEndIndex = $element['index'];
12✔
561

562
            do {
563
                $elementEndIndex = $tokens->getNextMeaningfulToken($elementEndIndex);
12✔
564
            } while ($tokens[$elementEndIndex]->isGivenKind([T_STRING, T_NS_SEPARATOR]) || $tokens[$elementEndIndex]->equals(','));
12✔
565

566
            if (!$tokens[$elementEndIndex]->equals(';')) {
12✔
567
                $elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($element['index'], ['{']));
3✔
568
            }
569
        } else { // 'const', 'property', enum-'case', or 'method' of an interface
570
            $elementEndIndex = $tokens->getNextTokenOfKind($element['index'], [';', '{']);
52✔
571
        }
572

573
        $singleLineElement = true;
92✔
574

575
        for ($i = $element['index'] + 1; $i < $elementEndIndex; ++$i) {
92✔
576
            if (str_contains($tokens[$i]->getContent(), "\n")) {
72✔
577
                $singleLineElement = false;
30✔
578

579
                break;
30✔
580
            }
581
        }
582

583
        if ($singleLineElement) {
92✔
584
            while (true) {
77✔
585
                $nextToken = $tokens[$elementEndIndex + 1];
77✔
586

587
                if (($nextToken->isComment() || $nextToken->isWhitespace()) && !str_contains($nextToken->getContent(), "\n")) {
77✔
588
                    ++$elementEndIndex;
14✔
589
                } else {
590
                    break;
77✔
591
                }
592
            }
593

594
            if ($tokens[$elementEndIndex]->isWhitespace()) {
77✔
595
                $elementEndIndex = $tokens->getPrevNonWhitespace($elementEndIndex);
2✔
596
            }
597
        }
598

599
        return $elementEndIndex;
92✔
600
    }
601
}
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