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

j-schumann / symfony-addons / 19030326024

03 Nov 2025 09:45AM UTC coverage: 54.081%. Remained the same
19030326024

push

github

j-schumann
upd: deps
upd: apply rector

0 of 2 new or added lines in 2 files covered. (0.0%)

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
140
        return !$this->areArgumentsAlreadyFormatted($tokens, $openParenIndex, $closeParenIndex, $analysisResult['topLevelCommas']);
×
141
    }
142

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

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

164
        return false;
×
165
    }
166

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

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

193
        // Detect indentation unit (try to find consistent indentation in the file)
194
        $indentUnit = $this->detectIndentationUnit($tokens);
×
195

196
        return [
×
197
            'base'     => $baseIndent,
×
198
            'unit'     => $indentUnit,
×
199
            'argument' => $baseIndent.$indentUnit,
×
200
        ];
×
201
    }
202

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

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

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

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

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

238
                if ('' !== $indent) {
×
239
                    $indentations[] = $indent;
×
240
                }
241
            }
242
        }
243

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

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

256
        // Count spaces - find the smallest non-zero indentation
NEW
257
        $spaceCounts = array_map(strlen(...), $indentations);
×
258
        $spaceCounts = array_filter($spaceCounts, static fn ($count) => $count > 0);
×
259

260
        if ([] === $spaceCounts) {
×
261
            return '    '; // Default to 4 spaces
×
262
        }
263

264
        $minSpaces = min($spaceCounts);
×
265

266
        return str_repeat(' ', $minSpaces);
×
267
    }
268

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

282
        for ($i = $openParenIndex + 1; $i < $closeParenIndex; ++$i) {
×
283
            $token = $tokens[$i];
×
284
            $content = $token->getContent();
×
285

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

296
            if (!$token->isWhitespace()) {
×
297
                $hasContent = true;
×
298
            }
299
        }
300

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

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

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

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

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

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

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

367
    /**
368
     * @param Tokens<Token> $tokens
369
     */
370
    private function replaceWhitespaceWithNewline(Tokens $tokens, int $whitespaceIndex, string $indent): void
371
    {
372
        if ($tokens[$whitespaceIndex]->isWhitespace()) {
×
373
            $content = $tokens[$whitespaceIndex]->getContent();
×
374
            if (!str_contains($content, "\n")) {
×
375
                $tokens[$whitespaceIndex] = new Token([\T_WHITESPACE, "\n".$indent]);
×
376
            }
377
        }
378
    }
379
}
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