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

j-schumann / symfony-addons / 16398599903

20 Jul 2025 09:49AM UTC coverage: 54.081% (+0.2%) from 53.846%
16398599903

push

github

j-schumann
fix: CS
upd: dependencies

1 of 6 new or added lines in 2 files covered. (16.67%)

497 of 919 relevant lines covered (54.08%)

3.45 hits per line

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

0.0
/src/PhpCsFixer/WrapNamedMethodArgumentsFixer.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Vrok\SymfonyAddons\PhpCsFixer;
6

7
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
8
use PhpCsFixer\Fixer\FixerInterface;
9
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
10
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
11
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
12
use PhpCsFixer\FixerDefinition\CodeSample;
13
use PhpCsFixer\FixerDefinition\FixerDefinition;
14
use PhpCsFixer\Tokenizer\Token;
15
use PhpCsFixer\Tokenizer\Tokens;
16

17
final class WrapNamedMethodArgumentsFixer implements FixerInterface, ConfigurableFixerInterface
18
{
19
    private const int DEFAULT_MAX_ARGUMENTS = 3;
20
    private const array NESTING_OPEN_TOKENS = ['(', '[', '{'];
21
    private const array NESTING_CLOSE_TOKENS = [')', ']', '}'];
22

23
    private int $maxArguments = self::DEFAULT_MAX_ARGUMENTS;
24

25
    public function getDefinition(): FixerDefinition
26
    {
27
        return new FixerDefinition(
×
28
            'Wrap method arguments to separate lines when they are named and exceed the maximum argument count (default 3).',
×
29
            [
×
30
                new CodeSample(
×
31
                    '<?php
×
32
$this->method(arg1: $value1, arg2: $value2, arg3: $value3);
33
// will be changed to:
34
$this->method(
35
    arg1: $value1,
36
    arg2: $value2,
37
    arg3: $value3
38
);
39

40
// will stay unchanged:
41
$this->method(arg1: $value1, arg2: $value2);',
×
42
                    ['max_arguments' => 2]
×
43
                ),
×
44
            ]
×
45
        );
×
46
    }
47

48
    public function getName(): string
49
    {
50
        return 'VrokSymfonyAddons/wrap_named_method_arguments';
×
51
    }
52

53
    public function getPriority(): int
54
    {
55
        return 100;
×
56
    }
57

58
    public function supports(\SplFileInfo $file): bool
59
    {
60
        return true;
×
61
    }
62

63
    /**
64
     * @param Tokens<Token> $tokens
65
     */
66
    public function isCandidate(Tokens $tokens): bool
67
    {
68
        return $tokens->isTokenKindFound(\T_STRING);
×
69
    }
70

71
    public function isRisky(): bool
72
    {
73
        return false;
×
74
    }
75

76
    public function getConfigurationDefinition(): FixerConfigurationResolverInterface
77
    {
78
        return new FixerConfigurationResolver([
×
79
            (new FixerOptionBuilder(
×
80
                'max_arguments',
×
81
                'Maximum number of arguments before formatting is applied.'
×
82
            ))
×
83
                ->setAllowedTypes(['int'])
×
84
                ->setDefault(self::DEFAULT_MAX_ARGUMENTS)
×
85
                ->getOption(),
×
86
        ]);
×
87
    }
88

89
    public function configure(array $configuration): void
90
    {
91
        $this->maxArguments = $configuration['max_arguments'] ?? self::DEFAULT_MAX_ARGUMENTS;
×
92
    }
93

94
    /**
95
     * @param Tokens<Token> $tokens
96
     */
97
    public function fix(\SplFileInfo $file, Tokens $tokens): void
98
    {
99
        for ($i = 0, $tokenCount = $tokens->count(); $i < $tokenCount; ++$i) {
×
100
            if (!$tokens[$i]->isGivenKind(\T_STRING)) {
×
101
                continue;
×
102
            }
103

104
            $openParenIndex = $tokens->getNextMeaningfulToken($i);
×
105
            if (
106
                null === $openParenIndex
×
107
                || !$tokens[$openParenIndex]->equals('(')
×
108
            ) {
109
                continue;
×
110
            }
111

112
            $closeParenIndex = $tokens->findBlockEnd(
×
113
                Tokens::BLOCK_TYPE_PARENTHESIS_BRACE,
×
114
                $openParenIndex
×
115
            );
×
116

117
            if ($this->shouldFormatMethodCall($tokens, $openParenIndex, $closeParenIndex)) {
×
118
                $indentation = $this->detectIndentation($tokens, $i);
×
119
                $this->formatMethodCall($tokens, $openParenIndex, $closeParenIndex, $indentation);
×
120
            }
121
        }
122
    }
123

124
    /**
125
     * @param Tokens<Token> $tokens
126
     */
127
    private function shouldFormatMethodCall(
128
        Tokens $tokens,
129
        int $openParenIndex,
130
        int $closeParenIndex,
131
    ): bool {
132
        $analysisResult = $this->analyzeArguments($tokens, $openParenIndex, $closeParenIndex);
×
133

134
        // Only format if we have named args and exceed the threshold
135
        if (!$analysisResult['hasNamedArgs'] || $analysisResult['argumentCount'] <= $this->maxArguments) {
×
136
            return false;
×
137
        }
138

139
        // Check if arguments are already on separate lines
NEW
140
        return !$this->areArgumentsAlreadyFormatted($tokens, $openParenIndex, $closeParenIndex, $analysisResult['topLevelCommas']);
×
141
    }
142

143
    private function areArgumentsAlreadyFormatted(Tokens $tokens, int $openParenIndex, int $closeParenIndex, array $topLevelCommas): bool
144
    {
145
        // Check if there's a newline after the opening parenthesis
146
        $nextIndex = $openParenIndex + 1;
×
NEW
147
        if ($nextIndex < $closeParenIndex && $tokens[$nextIndex]->isWhitespace() && str_contains($tokens[$nextIndex]->getContent(), "\n")) {
×
148
            // There's a newline after opening paren, likely already formatted
NEW
149
            return true;
×
150
        }
151

152
        // Check if there are newlines after commas
153
        foreach ($topLevelCommas as $commaIndex) {
×
154
            $nextIndex = $commaIndex + 1;
×
NEW
155
            if ($nextIndex < $closeParenIndex && $tokens[$nextIndex]->isWhitespace() && str_contains($tokens[$nextIndex]->getContent(), "\n")) {
×
156
                // Found newline after comma, likely already formatted
NEW
157
                return true;
×
158
            }
159
        }
160

161
        return false;
×
162
    }
163

164
    /**
165
     * @param Tokens<Token> $tokens
166
     */
167
    private function detectIndentation(Tokens $tokens, int $functionNameIndex): array
168
    {
169
        // Find the start of the line containing the function call
170
        $lineStartIndex = $functionNameIndex;
×
171
        while ($lineStartIndex > 0) {
×
172
            $prevIndex = $lineStartIndex - 1;
×
173
            if (
174
                $tokens[$prevIndex]->isWhitespace()
×
175
                && str_contains($tokens[$prevIndex]->getContent(), "\n")
×
176
            ) {
177
                break;
×
178
            }
179
            --$lineStartIndex;
×
180
        }
181

182
        // Detect current line indentation
183
        $baseIndent = '';
×
184
        if ($lineStartIndex > 0 && $tokens[$lineStartIndex]->isWhitespace()) {
×
185
            $whitespace = $tokens[$lineStartIndex]->getContent();
×
186
            $lines = explode("\n", $whitespace);
×
187
            $baseIndent = end($lines); // Get indentation after the last newline
×
188
        }
189

190
        // Detect indentation unit (try to find consistent indentation in the file)
191
        $indentUnit = $this->detectIndentationUnit($tokens);
×
192

193
        return [
×
194
            'base'     => $baseIndent,
×
195
            'unit'     => $indentUnit,
×
196
            'argument' => $baseIndent.$indentUnit,
×
197
        ];
×
198
    }
199

200
    /**
201
     * @param Tokens<Token> $tokens
202
     */
203
    private function detectIndentationUnit(Tokens $tokens): string
204
    {
205
        $indentations = [];
×
206

207
        // Sample some whitespace tokens to detect indentation pattern
208
        for ($i = 0, $count = min(100, $tokens->count()); $i < $count; ++$i) {
×
209
            if (!$tokens[$i]->isWhitespace()) {
×
210
                continue;
×
211
            }
212

213
            $content = $tokens[$i]->getContent();
×
214
            if (!str_contains($content, "\n")) {
×
215
                continue;
×
216
            }
217

218
            $lines = explode("\n", $content);
×
219
            foreach ($lines as $line) {
×
220
                if ('' === $line) {
×
221
                    continue;
×
222
                }
223

224
                // Count leading spaces/tabs
225
                $indent = '';
×
226
                $len = \strlen($line);
×
227
                for ($j = 0; $j < $len; ++$j) {
×
228
                    if (' ' === $line[$j] || "\t" === $line[$j]) {
×
229
                        $indent .= $line[$j];
×
230
                    } else {
231
                        break;
×
232
                    }
233
                }
234

235
                if ('' !== $indent) {
×
236
                    $indentations[] = $indent;
×
237
                }
238
            }
239
        }
240

241
        // Analyze indentations to find the unit
242
        if ([] === $indentations) {
×
243
            return '    '; // Default to 4 spaces
×
244
        }
245

246
        // Check if using tabs
247
        foreach ($indentations as $indent) {
×
248
            if (str_contains($indent, "\t")) {
×
249
                return "\t";
×
250
            }
251
        }
252

253
        // Count spaces - find the smallest non-zero indentation
254
        $spaceCounts = array_map('strlen', $indentations);
×
255
        $spaceCounts = array_filter($spaceCounts, static fn ($count) => $count > 0);
×
256

257
        if ([] === $spaceCounts) {
×
258
            return '    '; // Default to 4 spaces
×
259
        }
260

261
        $minSpaces = min($spaceCounts);
×
262

263
        return str_repeat(' ', $minSpaces);
×
264
    }
265

266
    /**
267
     * @param Tokens<Token> $tokens
268
     */
269
    private function analyzeArguments(
270
        Tokens $tokens,
271
        int $openParenIndex,
272
        int $closeParenIndex,
273
    ): array {
274
        $topLevelCommas = [];
×
275
        $nestingLevel = 0;
×
276
        $hasContent = false;
×
277
        $hasNamedArgs = false;
×
278

279
        for ($i = $openParenIndex + 1; $i < $closeParenIndex; ++$i) {
×
280
            $token = $tokens[$i];
×
281
            $content = $token->getContent();
×
282

283
            if (\in_array($content, self::NESTING_OPEN_TOKENS, true)) {
×
284
                ++$nestingLevel;
×
285
            } elseif (\in_array($content, self::NESTING_CLOSE_TOKENS, true)) {
×
286
                --$nestingLevel;
×
287
            } elseif (',' === $content && 0 === $nestingLevel) {
×
288
                $topLevelCommas[] = $i;
×
289
            } elseif (':' === $content) {
×
290
                $hasNamedArgs = true;
×
291
            }
292

293
            if (!$token->isWhitespace()) {
×
294
                $hasContent = true;
×
295
            }
296
        }
297

298
        return [
×
299
            'argumentCount'  => $hasContent ? \count($topLevelCommas) + 1 : 0,
×
300
            'hasNamedArgs'   => $hasNamedArgs,
×
301
            'topLevelCommas' => $topLevelCommas,
×
302
        ];
×
303
    }
304

305
    /**
306
     * @param Tokens<Token> $tokens
307
     */
308
    private function formatMethodCall(Tokens $tokens, int $openParenIndex, int $closeParenIndex, array $indentation): void
309
    {
310
        $analysisResult = $this->analyzeArguments($tokens, $openParenIndex, $closeParenIndex);
×
311
        $topLevelCommas = $analysisResult['topLevelCommas'];
×
312

313
        // Work backwards to avoid index shifts
314
        $this->addNewlineBeforeClosingParenthesis($tokens, $closeParenIndex, $indentation['base']);
×
315
        $this->addNewlinesAfterCommas($tokens, $topLevelCommas, $indentation['argument']);
×
316
        $this->addNewlineAfterOpeningParenthesis($tokens, $openParenIndex, $indentation['argument']);
×
317
    }
318

319
    /**
320
     * @param Tokens<Token> $tokens
321
     */
322
    private function addNewlineBeforeClosingParenthesis(Tokens $tokens, int $closeParenIndex, string $baseIndent): void
323
    {
324
        $prevIndex = $tokens->getPrevMeaningfulToken($closeParenIndex);
×
325
        if (null === $prevIndex) {
×
326
            return;
×
327
        }
328

329
        if ($prevIndex + 1 === $closeParenIndex) {
×
330
            $tokens->insertAt($closeParenIndex, new Token([\T_WHITESPACE, "\n".$baseIndent]));
×
331
        } else {
332
            $this->replaceWhitespaceWithNewline($tokens, $prevIndex + 1, $baseIndent);
×
333
        }
334
    }
335

336
    /**
337
     * @param Tokens<Token> $tokens
338
     */
339
    private function addNewlinesAfterCommas(Tokens $tokens, array $topLevelCommas, string $argumentIndent): void
340
    {
341
        foreach (array_reverse($topLevelCommas) as $commaIndex) {
×
342
            $nextTokenIndex = $commaIndex + 1;
×
343
            if ($nextTokenIndex < \count($tokens) && $tokens[$nextTokenIndex]->isWhitespace()) {
×
344
                $tokens[$nextTokenIndex] = new Token([\T_WHITESPACE, "\n".$argumentIndent]);
×
345
            } else {
346
                $tokens->insertAt($commaIndex + 1, new Token([\T_WHITESPACE, "\n".$argumentIndent]));
×
347
            }
348
        }
349
    }
350

351
    /**
352
     * @param Tokens<Token> $tokens
353
     */
354
    private function addNewlineAfterOpeningParenthesis(Tokens $tokens, int $openParenIndex, string $argumentIndent): void
355
    {
356
        $nextTokenIndex = $openParenIndex + 1;
×
357
        if ($nextTokenIndex < \count($tokens) && $tokens[$nextTokenIndex]->isWhitespace()) {
×
358
            $tokens[$nextTokenIndex] = new Token([\T_WHITESPACE, "\n".$argumentIndent]);
×
359
        } else {
360
            $tokens->insertAt($openParenIndex + 1, new Token([\T_WHITESPACE, "\n".$argumentIndent]));
×
361
        }
362
    }
363

364
    /**
365
     * @param Tokens<Token> $tokens
366
     */
367
    private function replaceWhitespaceWithNewline(Tokens $tokens, int $whitespaceIndex, string $indent): void
368
    {
369
        if ($tokens[$whitespaceIndex]->isWhitespace()) {
×
370
            $content = $tokens[$whitespaceIndex]->getContent();
×
371
            if (!str_contains($content, "\n")) {
×
372
                $tokens[$whitespaceIndex] = new Token([\T_WHITESPACE, "\n".$indent]);
×
373
            }
374
        }
375
    }
376
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc