Debian Codegraph @

vendor/zircote/swagger-php/src/Processors/Concerns/DocblockTrait.php

raw
1 <?php declare(strict_types=1);
2
3 /**
4 * @license Apache 2.0
5 */
6
7 namespace OpenApi\Processors\Concerns;
8
9 use OpenApi\Annotations as OA;
10 use OpenApi\Attributes as OAT;
11 use OpenApi\Generator;
12 use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
13 use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
14 use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode;
15 use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
16 use PHPStan\PhpDocParser\Ast\Type\TypeNode;
17 use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
18 use PHPStan\PhpDocParser\Lexer\Lexer;
19 use PHPStan\PhpDocParser\Parser\ConstExprParser;
20 use PHPStan\PhpDocParser\Parser\PhpDocParser;
21 use PHPStan\PhpDocParser\Parser\TokenIterator;
22 use PHPStan\PhpDocParser\Parser\TypeParser;
23 use PHPStan\PhpDocParser\ParserConfig;
24
25 trait DocblockTrait
26 {
27 /**
28 * An annotation is a docblock root if it is the top-level / outermost annotation in a PHP docblock.
29 */
30 public function isDocblockRoot(OA\AbstractAnnotation $annotation): bool
31 {
32 if (1 == count($annotation->_context->annotations)) {
33 return true;
34 }
35
36 /** @var array<class-string,bool> $matchPriorityMap */
37 $matchPriorityMap = [
38 OA\OpenApi::class,
39
40 OA\Operation::class => false,
41 OA\Property::class => false,
42 OA\Parameter::class => false,
43 OA\Response::class => false,
44
45 OA\Schema::class => true,
46 OAT\Schema::class => true,
47 ];
48 // try to find the best root match
49 foreach ($matchPriorityMap as $className => $strict) {
50 foreach ($annotation->_context->annotations as $contextAnnotation) {
51 if ($strict) {
52 if ($className === $contextAnnotation::class) {
53 return $annotation === $contextAnnotation;
54 }
55 } else {
56 if ($contextAnnotation instanceof $className) {
57 return $annotation === $contextAnnotation;
58 }
59 }
60 }
61 }
62
63 return false;
64 }
65
66 /**
67 * Parse a docblock string into a PhpDocNode.
68 */
69 protected function parsePhpDoc(?string $docblock): ?PhpDocNode
70 {
71 if (!$docblock || Generator::isDefault($docblock)) {
72 return null;
73 }
74
75 // Normalize single-star comments to PHPDoc format
76 $normalized = preg_replace('#^/\*(?!\*)#', '/**', $docblock);
77
78 // Ensure docblock has proper closing
79 if (!str_contains((string) $normalized, '*/')) {
80 $normalized = rtrim((string) $normalized) . '/';
81 }
82
83 $config = new ParserConfig([]);
84 $lexer = new Lexer($config);
85 $phpDocParser = new PhpDocParser(
86 $config,
87 new TypeParser($config, $constExprParser = new ConstExprParser($config)),
88 $constExprParser,
89 );
90
91 try {
92 $tokens = new TokenIterator($lexer->tokenize($normalized));
93
94 return $phpDocParser->parse($tokens);
95 } catch (\Throwable) {
96 return null;
97 }
98 }
99
100 /**
101 * Format a type node as a compact string (without wrapping parentheses for union/intersection types).
102 */
103 protected function formatType(TypeNode $typeNode): string
104 {
105 if ($typeNode instanceof UnionTypeNode) {
106 return implode('|', array_map(strval(...), $typeNode->types));
107 }
108
109 if ($typeNode instanceof IntersectionTypeNode) {
110 return implode('&', array_map(strval(...), $typeNode->types));
111 }
112
113 return (string) $typeNode;
114 }
115
116 /**
117 * Parse a docblock and return the full content/text.
118 */
119 public function parseDocblock(?string $docblock, ?array &$tags = null): string
120 {
121 $docNode = $this->parsePhpDoc($docblock);
122 if (!$docNode) {
123 return Generator::UNDEFINED;
124 }
125
126 // Extract @param tags if requested
127 if (null !== $tags) {
128 if (!array_key_exists('param', $tags)) {
129 $tags['param'] = [];
130 }
131 foreach ($docNode->getParamTagValues() as $param) {
132 $name = ltrim((string) $param->parameterName, '$');
133 $tags['param'][$name] = [
134 'type' => (string) $param->type ?: null,
135 'description' => $param->description !== '' ? $param->description : null,
136 ];
137 }
138 foreach ($docNode->getTypelessParamTagValues() as $param) {
139 $name = ltrim((string) $param->parameterName, '$');
140 $tags['param'][$name] = [
141 'type' => null,
142 'description' => $param->description !== '' ? $param->description : null,
143 ];
144 }
145 }
146
147 // Extract description from text nodes before first tag
148 $lines = [];
149 foreach ($docNode->children as $child) {
150 if ($child instanceof PhpDocTagNode) {
151 break;
152 }
153 if ($child instanceof PhpDocTextNode && $child->text !== '') {
154 $lines[] = $child->text;
155 }
156 }
157
158 $description = trim(implode("\n", $lines));
159 // Handle line continuation with trailing backslash
160 $description = preg_replace('/\\\\\n/', '', $description);
161
162 return $description === ''
163 ? Generator::UNDEFINED
164 : $description;
165 }
166
167 /**
168 * A short piece of text, usually one line, providing the basic function of the associated element.
169 *
170 * @param string $content The full docblock content
171 */
172 public function extractCommentSummary(string $content): string
173 {
174 if (Generator::isDefault($content)) {
175 return Generator::UNDEFINED;
176 }
177
178 $lines = preg_split('/(\n|\r\n)/', $content);
179 $summary = '';
180 foreach ($lines as $line) {
181 $summary .= $line . "\n";
182 if ($line === '' || str_ends_with($line, '.')) {
183 return trim($summary);
184 }
185 }
186 $summary = trim($summary);
187 if ($summary === '') {
188 return Generator::UNDEFINED;
189 }
190
191 return $summary;
192 }
193
194 /**
195 * An optional longer piece of text providing more details on the associated element's function.
196 *
197 * @param string $content The full docblock content
198 */
199 public function extractCommentDescription(string $content): string
200 {
201 if (Generator::isDefault($content)) {
202 return Generator::UNDEFINED;
203 }
204
205 $summary = $this->extractCommentSummary($content);
206 if (Generator::isDefault($summary)) {
207 return Generator::UNDEFINED;
208 }
209
210 $description = '';
211 if (($substr = substr($content, strlen((string) $summary))) !== '') {
212 $description = trim($substr);
213 }
214
215 return $description ?: Generator::UNDEFINED;
216 }
217
218 /**
219 * Extract property type and description from a <code>@var</code> dockblock line.
220 *
221 * @return array{type: ?string, description: ?string}
222 */
223 public function parseVarLine(?string $docblock): array
224 {
225 $result = ['type' => null, 'description' => null];
226
227 $docNode = $this->parsePhpDoc($docblock);
228 if (!$docNode) {
229 return $result;
230 }
231
232 $varTags = $docNode->getVarTagValues();
233 if ($varTags) {
234 $varTag = reset($varTags);
235 $type = $this->formatType($varTag->type);
236
237 $result['type'] = $type !== '' ? $type : null;
238 $result['description'] = $varTag->description !== '' ? trim((string) $varTag->description) : null;
239 }
240
241 return $result;
242 }
243
244 /**
245 * Extract example text from a <code>@example</code> dockblock line.
246 */
247 public function extractExampleDescription(string $docblock): ?string
248 {
249 $docNode = $this->parsePhpDoc($docblock);
250 if (!$docNode) {
251 return null;
252 }
253
254 foreach ($docNode->getTagsByName('@example') as $tag) {
255 $value = (string) $tag->value;
256
257 return $value !== '' ? trim($value) : null;
258 }
259
260 return null;
261 }
262
263 /**
264 * Returns true if the <code>@deprecated</code> tag is present, false otherwise.
265 */
266 public function isDeprecated(?string $docblock): bool
267 {
268 $docNode = $this->parsePhpDoc($docblock);
269 if (!$docNode) {
270 return false;
271 }
272
273 return count($docNode->getDeprecatedTagValues()) > 0;
274 }
275 }