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

keradus / PHP-CS-Fixer / 16839019843

06 Aug 2025 10:45PM UTC coverage: 94.73% (-0.02%) from 94.749%
16839019843

push

github

web-flow
feat: introduce `PER-CS3.0` rulsets (#8841)

21 of 21 new or added lines in 5 files covered. (100.0%)

241 existing lines in 18 files now uncovered.

28255 of 29827 relevant lines covered (94.73%)

45.87 hits per line

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

95.24
/src/DocBlock/Annotation.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\DocBlock;
16

17
use PhpCsFixer\Preg;
18
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
19
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
20

21
/**
22
 * This represents an entire annotation from a docblock.
23
 *
24
 * @author Graham Campbell <hello@gjcampbell.co.uk>
25
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
26
 */
27
final class Annotation
28
{
29
    /**
30
     * All the annotation tag names with types.
31
     *
32
     * @var list<string>
33
     */
34
    private const TAGS = [
35
        'extends',
36
        'implements',
37
        'method',
38
        'param',
39
        'param-out',
40
        'phpstan-type',
41
        'phpstan-import-type',
42
        'property',
43
        'property-read',
44
        'property-write',
45
        'psalm-type',
46
        'psalm-import-type',
47
        'return',
48
        'throws',
49
        'type',
50
        'var',
51
    ];
52

53
    /**
54
     * The lines that make up the annotation.
55
     *
56
     * @var non-empty-list<Line>
57
     */
58
    private array $lines;
59

60
    /**
61
     * The position of the first line of the annotation in the docblock.
62
     */
63
    private int $start;
64

65
    /**
66
     * The position of the last line of the annotation in the docblock.
67
     */
68
    private int $end;
69

70
    /**
71
     * The associated tag.
72
     */
73
    private ?Tag $tag = null;
74

75
    /**
76
     * Lazy loaded, cached types content.
77
     */
78
    private ?string $typesContent = null;
79

80
    /**
81
     * The cached types.
82
     *
83
     * @var null|list<string>
84
     */
85
    private ?array $types = null;
86

87
    private ?NamespaceAnalysis $namespace = null;
88

89
    /**
90
     * @var list<NamespaceUseAnalysis>
91
     */
92
    private array $namespaceUses;
93

94
    /**
95
     * Create a new line instance.
96
     *
97
     * @param non-empty-array<int, Line> $lines
98
     * @param null|NamespaceAnalysis     $namespace
99
     * @param list<NamespaceUseAnalysis> $namespaceUses
100
     */
101
    public function __construct(array $lines, $namespace = null, array $namespaceUses = [])
102
    {
103
        $this->lines = array_values($lines);
131✔
104
        $this->namespace = $namespace;
131✔
105
        $this->namespaceUses = $namespaceUses;
131✔
106

107
        $this->start = array_key_first($lines);
131✔
108
        $this->end = array_key_last($lines);
131✔
109
    }
110

111
    /**
112
     * Get the string representation of object.
113
     */
114
    public function __toString(): string
115
    {
116
        return $this->getContent();
5✔
117
    }
118

119
    /**
120
     * Get all the annotation tag names with types.
121
     *
122
     * @return list<string>
123
     */
124
    public static function getTagsWithTypes(): array
125
    {
126
        return self::TAGS;
1✔
127
    }
128

129
    /**
130
     * Get the start position of this annotation.
131
     */
132
    public function getStart(): int
133
    {
134
        return $this->start;
5✔
135
    }
136

137
    /**
138
     * Get the end position of this annotation.
139
     */
140
    public function getEnd(): int
141
    {
142
        return $this->end;
32✔
143
    }
144

145
    /**
146
     * Get the associated tag.
147
     */
148
    public function getTag(): Tag
149
    {
150
        if (null === $this->tag) {
104✔
151
            $this->tag = new Tag($this->lines[0]);
104✔
152
        }
153

154
        return $this->tag;
104✔
155
    }
156

157
    /**
158
     * @internal
159
     */
160
    public function getTypeExpression(): ?TypeExpression
161
    {
162
        $typesContent = $this->getTypesContent();
75✔
163

164
        return null === $typesContent
74✔
165
            ? null
×
166
            : new TypeExpression($typesContent, $this->namespace, $this->namespaceUses);
74✔
167
    }
168

169
    /**
170
     * @internal
171
     */
172
    public function getVariableName(): ?string
173
    {
174
        $type = preg_quote($this->getTypesContent() ?? '', '/');
23✔
175
        $regex = \sprintf(
23✔
176
            '/@%s\s+(%s\s*)?(&\s*)?(\.{3}\s*)?(?<variable>\$%s)(?:.*|$)/',
23✔
177
            $this->tag->getName(),
23✔
178
            $type,
23✔
179
            TypeExpression::REGEX_IDENTIFIER
23✔
180
        );
23✔
181

182
        if (Preg::match($regex, $this->lines[0]->getContent(), $matches)) {
23✔
183
            \assert(isset($matches['variable']));
21✔
184

185
            return $matches['variable'];
21✔
186
        }
187

188
        return null;
2✔
189
    }
190

191
    /**
192
     * Get the types associated with this annotation.
193
     *
194
     * @return list<string>
195
     */
196
    public function getTypes(): array
197
    {
198
        if (null === $this->types) {
59✔
199
            $typeExpression = $this->getTypeExpression();
59✔
200
            $this->types = null === $typeExpression
58✔
UNCOV
201
                ? []
×
202
                : $typeExpression->getTypes();
58✔
203
        }
204

205
        return $this->types;
58✔
206
    }
207

208
    /**
209
     * Set the types associated with this annotation.
210
     *
211
     * @param list<string> $types
212
     */
213
    public function setTypes(array $types): void
214
    {
215
        $origTypesContent = $this->getTypesContent();
8✔
216
        $newTypesContent = implode(
7✔
217
            // Fallback to union type is provided for backward compatibility (previously glue was set to `|` by default even when type was not composite)
218
            // @TODO Better handling for cases where type is fixed (original type is not composite, but was made composite during fix)
219
            $this->getTypeExpression()->getTypesGlue() ?? '|',
7✔
220
            $types
7✔
221
        );
7✔
222

223
        if ($origTypesContent === $newTypesContent) {
7✔
UNCOV
224
            return;
×
225
        }
226

227
        $originalTypesLines = Preg::split('/([^\n\r]+\R*)/', $origTypesContent, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
7✔
228
        $newTypesLines = Preg::split('/([^\n\r]+\R*)/', $newTypesContent, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
7✔
229

230
        \assert(\count($originalTypesLines) === \count($newTypesLines));
7✔
231

232
        foreach ($newTypesLines as $index => $line) {
7✔
233
            \assert(isset($originalTypesLines[$index]));
7✔
234
            $pattern = '/'.preg_quote($originalTypesLines[$index], '/').'/';
7✔
235

236
            \assert(isset($this->lines[$index]));
7✔
237
            $this->lines[$index]->setContent(Preg::replace($pattern, $line, $this->lines[$index]->getContent(), 1));
7✔
238
        }
239

240
        $this->clearCache();
7✔
241
    }
242

243
    /**
244
     * Get the normalized types associated with this annotation, so they can easily be compared.
245
     *
246
     * @return list<string>
247
     */
248
    public function getNormalizedTypes(): array
249
    {
250
        $typeExpression = $this->getTypeExpression();
13✔
251
        if (null === $typeExpression) {
13✔
UNCOV
252
            return [];
×
253
        }
254

255
        $normalizedTypeExpression = $typeExpression
13✔
256
            ->mapTypes(static fn (TypeExpression $v) => new TypeExpression(strtolower($v->toString()), null, []))
13✔
257
            ->sortTypes(static fn (TypeExpression $a, TypeExpression $b) => $a->toString() <=> $b->toString())
13✔
258
        ;
13✔
259

260
        return $normalizedTypeExpression->getTypes();
13✔
261
    }
262

263
    /**
264
     * Remove this annotation by removing all its lines.
265
     */
266
    public function remove(): void
267
    {
268
        foreach ($this->lines as $line) {
12✔
269
            if ($line->isTheStart() && $line->isTheEnd()) {
12✔
270
                // Single line doc block, remove entirely
271
                $line->remove();
3✔
272
            } elseif ($line->isTheStart()) {
9✔
273
                // Multi line doc block, but start is on the same line as the first annotation, keep only the start
274
                $content = Preg::replace('#(\s*/\*\*).*#', '$1', $line->getContent());
2✔
275

276
                $line->setContent($content);
2✔
277
            } elseif ($line->isTheEnd()) {
7✔
278
                // Multi line doc block, but end is on the same line as the last annotation, keep only the end
279
                $content = Preg::replace('#(\s*)\S.*(\*/.*)#', '$1$2', $line->getContent());
2✔
280

281
                $line->setContent($content);
2✔
282
            } else {
283
                // Multi line doc block, neither start nor end on this line, can be removed safely
284
                $line->remove();
5✔
285
            }
286
        }
287

288
        $this->clearCache();
12✔
289
    }
290

291
    /**
292
     * Get the annotation content.
293
     */
294
    public function getContent(): string
295
    {
296
        return implode('', $this->lines);
107✔
297
    }
298

299
    public function supportTypes(): bool
300
    {
301
        return \in_array($this->getTag()->getName(), self::TAGS, true);
99✔
302
    }
303

304
    /**
305
     * Get the current types content.
306
     *
307
     * Be careful modifying the underlying line as that won't flush the cache.
308
     */
309
    private function getTypesContent(): ?string
310
    {
311
        if (null === $this->typesContent) {
99✔
312
            $name = $this->getTag()->getName();
99✔
313

314
            if (!$this->supportTypes()) {
99✔
315
                throw new \RuntimeException('This tag does not support types.');
2✔
316
            }
317

318
            if (Preg::match(
97✔
319
                '{^(?:\h*\*|/\*\*)[\h*]*@'.$name.'\h+'.TypeExpression::REGEX_TYPES.'(?:(?:[*\h\v]|\&?[\.\$\s]).*)?\r?$}is',
97✔
320
                $this->getContent(),
97✔
321
                $matches
97✔
322
            )) {
97✔
323
                \assert(isset($matches['types']));
94✔
324
                $this->typesContent = $matches['types'];
94✔
325
            }
326
        }
327

328
        return $this->typesContent;
97✔
329
    }
330

331
    private function clearCache(): void
332
    {
333
        $this->types = null;
19✔
334
        $this->typesContent = null;
19✔
335
    }
336
}
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