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

keradus / PHP-CS-Fixer / 13614616960

01 Mar 2025 10:06PM UTC coverage: 94.929% (-0.03%) from 94.959%
13614616960

push

github

keradus
bumped version

28060 of 29559 relevant lines covered (94.93%)

43.05 hits per line

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

97.8
/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.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\Whitespace;
16

17
use PhpCsFixer\AbstractFixer;
18
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
19
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
20
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
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\Tokenizer\Analyzer\Analysis\TypeAnalysis;
30
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
31
use PhpCsFixer\Tokenizer\Token;
32
use PhpCsFixer\Tokenizer\Tokens;
33
use PhpCsFixer\Tokenizer\TokensAnalyzer;
34

35
/**
36
 * @author Dariusz RumiƄski <dariusz.ruminski@gmail.com>
37
 * @author John Paul E. Balandan, CPA <paulbalandan@gmail.com>
38
 *
39
 * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
40
 *
41
 * @phpstan-type _AutogeneratedInputConfiguration array{
42
 *  elements?: list<'constant'|'function'|'property'>
43
 * }
44
 * @phpstan-type _AutogeneratedComputedConfiguration array{
45
 *  elements: list<'constant'|'function'|'property'>
46
 * }
47
 */
48
final class TypeDeclarationSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface
49
{
50
    /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
51
    use ConfigurableFixerTrait;
52

53
    public function getDefinition(): FixerDefinitionInterface
54
    {
55
        return new FixerDefinition(
3✔
56
            'Ensure single space between a variable and its type declaration in function arguments and properties.',
3✔
57
            [
3✔
58
                new CodeSample(
3✔
59
                    '<?php
3✔
60
class Bar
61
{
62
    private string    $a;
63
    private bool   $b;
64

65
    public function __invoke(array   $c) {}
66
}
67
'
3✔
68
                ),
3✔
69
                new CodeSample(
3✔
70
                    '<?php
3✔
71
class Foo
72
{
73
    public int   $bar;
74

75
    public function baz(string     $a)
76
    {
77
        return fn(bool    $c): string => (string) $c;
78
    }
79
}
80
',
3✔
81
                    ['elements' => ['function']]
3✔
82
                ),
3✔
83
                new CodeSample(
3✔
84
                    '<?php
3✔
85
class Foo
86
{
87
    public int   $bar;
88

89
    public function baz(string     $a) {}
90
}
91
',
3✔
92
                    ['elements' => ['property']]
3✔
93
                ),
3✔
94
                new VersionSpecificCodeSample(
3✔
95
                    '<?php
3✔
96
class Foo
97
{
98
    public  const string   BAR = "";
99
}
100
',
3✔
101
                    new VersionSpecification(8_03_00),
3✔
102
                    ['elements' => ['constant']]
3✔
103
                ),
3✔
104
            ]
3✔
105
        );
3✔
106
    }
107

108
    public function isCandidate(Tokens $tokens): bool
109
    {
110
        return $tokens->isAnyTokenKindsFound([...Token::getClassyTokenKinds(), T_FN, T_FUNCTION]);
87✔
111
    }
112

113
    protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
114
    {
115
        return new FixerConfigurationResolver([
95✔
116
            (new FixerOptionBuilder('elements', 'Structural elements where the spacing after the type declaration should be fixed.'))
95✔
117
                ->setAllowedTypes(['string[]'])
95✔
118
                ->setAllowedValues([new AllowedValueSubset(['function', 'property', 'constant'])])
95✔
119
                ->setDefault(['function', 'property']) // @TODO add 'constant' on next major 4.0
95✔
120
                ->getOption(),
95✔
121
        ]);
95✔
122
    }
123

124
    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
125
    {
126
        $functionsAnalyzer = new FunctionsAnalyzer();
85✔
127

128
        foreach (array_reverse($this->getElements($tokens), true) as $index => $type) {
85✔
129
            if ('property' === $type && \in_array('property', $this->configuration['elements'], true)) {
85✔
130
                $this->ensureSingleSpaceAtPropertyTypehint($tokens, $index);
17✔
131

132
                continue;
17✔
133
            }
134

135
            if ('method' === $type && \in_array('function', $this->configuration['elements'], true)) {
71✔
136
                $this->ensureSingleSpaceAtFunctionArgumentTypehint($functionsAnalyzer, $tokens, $index);
51✔
137

138
                continue;
51✔
139
            }
140

141
            if ('const' === $type && \in_array('constant', $this->configuration['elements'], true)) {
22✔
142
                $this->ensureSingleSpaceAtConstantTypehint($tokens, $index);
22✔
143

144
                // implicit continue;
145
            }
146
        }
147
    }
148

149
    /**
150
     * @return array<int, string>
151
     *
152
     * @phpstan-return array<int, 'method'|'property'|'const'>
153
     */
154
    private function getElements(Tokens $tokens): array
155
    {
156
        $tokensAnalyzer = new TokensAnalyzer($tokens);
85✔
157

158
        $elements = array_map(
85✔
159
            static fn (array $element): string => $element['type'],
85✔
160
            array_filter(
85✔
161
                $tokensAnalyzer->getClassyElements(),
85✔
162
                static fn (array $element): bool => \in_array($element['type'], ['method', 'property', 'const'], true)
85✔
163
            )
85✔
164
        );
85✔
165

166
        foreach ($tokens as $index => $token) {
85✔
167
            if (
168
                $token->isGivenKind(T_FN)
85✔
169
                || ($token->isGivenKind(T_FUNCTION) && !isset($elements[$index]))
85✔
170
            ) {
171
                $elements[$index] = 'method';
47✔
172
            }
173
        }
174

175
        return $elements;
85✔
176
    }
177

178
    private function ensureSingleSpaceAtFunctionArgumentTypehint(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void
179
    {
180
        foreach (array_reverse($functionsAnalyzer->getFunctionArguments($tokens, $index)) as $argumentInfo) {
51✔
181
            $argumentType = $argumentInfo->getTypeAnalysis();
50✔
182

183
            if (null === $argumentType) {
50✔
184
                continue;
11✔
185
            }
186

187
            $tokens->ensureWhitespaceAtIndex($argumentType->getEndIndex() + 1, 0, ' ');
43✔
188
        }
189
    }
190

191
    private function ensureSingleSpaceAtPropertyTypehint(Tokens $tokens, int $index): void
192
    {
193
        $propertyIndex = $index;
17✔
194
        $propertyModifiers = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, T_VAR];
17✔
195

196
        if (\defined('T_READONLY')) {
17✔
197
            $propertyModifiers[] = T_READONLY; // @TODO drop condition when PHP 8.1 is supported
17✔
198
        }
199

200
        do {
201
            $index = $tokens->getPrevMeaningfulToken($index);
17✔
202
        } while (!$tokens[$index]->isGivenKind($propertyModifiers));
17✔
203

204
        $propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyIndex);
17✔
205

206
        if (null === $propertyType) {
17✔
207
            return;
3✔
208
        }
209

210
        $tokens->ensureWhitespaceAtIndex($propertyType->getEndIndex() + 1, 0, ' ');
14✔
211
    }
212

213
    private function ensureSingleSpaceAtConstantTypehint(Tokens $tokens, int $index): void
214
    {
215
        $constIndex = $index;
22✔
216
        $equalsIndex = $tokens->getNextTokenOfKind($constIndex, ['=']);
22✔
217

218
        if (null === $equalsIndex) {
22✔
219
            return;
×
220
        }
221

222
        $nameIndex = $tokens->getPrevMeaningfulToken($equalsIndex);
22✔
223

224
        if (!$tokens[$nameIndex]->isGivenKind(T_STRING)) {
22✔
225
            return;
×
226
        }
227

228
        $typeEndIndex = $tokens->getPrevMeaningfulToken($nameIndex);
22✔
229

230
        if (null === $typeEndIndex || $tokens[$typeEndIndex]->isGivenKind(T_CONST)) {
22✔
231
            return;
5✔
232
        }
233

234
        $tokens->ensureWhitespaceAtIndex($typeEndIndex + 1, 0, ' ');
17✔
235
    }
236

237
    private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex): ?TypeAnalysis
238
    {
239
        $type = '';
17✔
240
        $typeStartIndex = $tokens->getNextMeaningfulToken($startIndex);
17✔
241
        $typeEndIndex = $typeStartIndex;
17✔
242

243
        for ($i = $typeStartIndex; $i < $endIndex; ++$i) {
17✔
244
            if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) {
14✔
245
                continue;
14✔
246
            }
247

248
            $type .= $tokens[$i]->getContent();
14✔
249
            $typeEndIndex = $i;
14✔
250
        }
251

252
        return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null;
17✔
253
    }
254
}
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