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

keradus / PHP-CS-Fixer / 16303177127

15 Jul 2025 06:22PM UTC coverage: 94.758% (-0.05%) from 94.806%
16303177127

push

github

keradus
bumped version

28199 of 29759 relevant lines covered (94.76%)

45.91 hits per line

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

94.87
/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 array<int, 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 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);
130✔
104
        $this->namespace = $namespace;
130✔
105
        $this->namespaceUses = $namespaceUses;
130✔
106

107
        $this->start = array_key_first($lines);
130✔
108
        $this->end = array_key_last($lines);
130✔
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) {
103✔
151
            $this->tag = new Tag($this->lines[0]);
103✔
152
        }
153

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

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

164
        return null === $typesContent
73✔
165
            ? null
×
166
            : new TypeExpression($typesContent, $this->namespace, $this->namespaceUses);
73✔
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
            return $matches['variable'];
21✔
184
        }
185

186
        return null;
2✔
187
    }
188

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

203
        return $this->types;
57✔
204
    }
205

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

221
        if ($origTypesContent === $newTypesContent) {
7✔
222
            return;
×
223
        }
224

225
        $pattern = '/'.preg_quote($origTypesContent, '/').'/';
7✔
226

227
        $this->lines[0]->setContent(Preg::replace($pattern, $newTypesContent, $this->lines[0]->getContent(), 1));
7✔
228

229
        $this->clearCache();
7✔
230
    }
231

232
    /**
233
     * Get the normalized types associated with this annotation, so they can easily be compared.
234
     *
235
     * @return list<string>
236
     */
237
    public function getNormalizedTypes(): array
238
    {
239
        $typeExpression = $this->getTypeExpression();
13✔
240
        if (null === $typeExpression) {
13✔
241
            return [];
×
242
        }
243

244
        $normalizedTypeExpression = $typeExpression
13✔
245
            ->mapTypes(static fn (TypeExpression $v) => new TypeExpression(strtolower($v->toString()), null, []))
13✔
246
            ->sortTypes(static fn (TypeExpression $a, TypeExpression $b) => $a->toString() <=> $b->toString())
13✔
247
        ;
13✔
248

249
        return $normalizedTypeExpression->getTypes();
13✔
250
    }
251

252
    /**
253
     * Remove this annotation by removing all its lines.
254
     */
255
    public function remove(): void
256
    {
257
        foreach ($this->lines as $line) {
12✔
258
            if ($line->isTheStart() && $line->isTheEnd()) {
12✔
259
                // Single line doc block, remove entirely
260
                $line->remove();
3✔
261
            } elseif ($line->isTheStart()) {
9✔
262
                // Multi line doc block, but start is on the same line as the first annotation, keep only the start
263
                $content = Preg::replace('#(\s*/\*\*).*#', '$1', $line->getContent());
2✔
264

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

270
                $line->setContent($content);
2✔
271
            } else {
272
                // Multi line doc block, neither start nor end on this line, can be removed safely
273
                $line->remove();
5✔
274
            }
275
        }
276

277
        $this->clearCache();
12✔
278
    }
279

280
    /**
281
     * Get the annotation content.
282
     */
283
    public function getContent(): string
284
    {
285
        return implode('', $this->lines);
10✔
286
    }
287

288
    public function supportTypes(): bool
289
    {
290
        return \in_array($this->getTag()->getName(), self::TAGS, true);
98✔
291
    }
292

293
    /**
294
     * Get the current types content.
295
     *
296
     * Be careful modifying the underlying line as that won't flush the cache.
297
     */
298
    private function getTypesContent(): ?string
299
    {
300
        if (null === $this->typesContent) {
98✔
301
            $name = $this->getTag()->getName();
98✔
302

303
            if (!$this->supportTypes()) {
98✔
304
                throw new \RuntimeException('This tag does not support types.');
2✔
305
            }
306

307
            $matchingResult = Preg::match(
96✔
308
                '{^(?:\h*\*|/\*\*)[\h*]*@'.$name.'\h+'.TypeExpression::REGEX_TYPES.'(?:(?:[*\h\v]|\&?[\.\$\s]).*)?\r?$}is',
96✔
309
                $this->lines[0]->getContent(),
96✔
310
                $matches
96✔
311
            );
96✔
312

313
            $this->typesContent = $matchingResult
96✔
314
                ? $matches['types']
93✔
315
                : null;
3✔
316
        }
317

318
        return $this->typesContent;
96✔
319
    }
320

321
    private function clearCache(): void
322
    {
323
        $this->types = null;
19✔
324
        $this->typesContent = null;
19✔
325
    }
326
}
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