Debian Codegraph @

lib/3rdParty/composer/phpdocumentor/reflection-docblock/src/DocBlockFactory.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 /**
6 * This file is part of phpDocumentor.
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 *
11 * @link http://phpdoc.org
12 */
13
14 namespace phpDocumentor\Reflection;
15
16 use InvalidArgumentException;
17 use LogicException;
18 use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
19 use phpDocumentor\Reflection\DocBlock\StandardTagFactory;
20 use phpDocumentor\Reflection\DocBlock\Tag;
21 use phpDocumentor\Reflection\DocBlock\TagFactory;
22 use phpDocumentor\Reflection\DocBlock\Tags\Factory\Factory;
23 use Webmozart\Assert\Assert;
24
25 use function array_shift;
26 use function count;
27 use function explode;
28 use function is_object;
29 use function method_exists;
30 use function preg_match;
31 use function preg_replace;
32 use function str_replace;
33 use function strpos;
34 use function substr;
35 use function trim;
36
37 final class DocBlockFactory implements DocBlockFactoryInterface
38 {
39 private DocBlock\DescriptionFactory $descriptionFactory;
40
41 private TagFactory $tagFactory;
42
43 /**
44 * Initializes this factory with the required subcontractors.
45 */
46 public function __construct(DescriptionFactory $descriptionFactory, TagFactory $tagFactory)
47 {
48 $this->descriptionFactory = $descriptionFactory;
49 $this->tagFactory = $tagFactory;
50 }
51
52 /**
53 * Factory method for easy instantiation.
54 *
55 * @param array<string, class-string<Tag>|Factory> $additionalTags
56 */
57 public static function createInstance(array $additionalTags = []): DocBlockFactoryInterface
58 {
59 $fqsenResolver = new FqsenResolver();
60 $tagFactory = StandardTagFactory::createInstance($fqsenResolver);
61 $descriptionFactory = new DescriptionFactory($tagFactory);
62
63 $docBlockFactory = new self($descriptionFactory, $tagFactory);
64 foreach ($additionalTags as $tagName => $tagHandler) {
65 $docBlockFactory->registerTagHandler($tagName, $tagHandler);
66 }
67
68 return $docBlockFactory;
69 }
70
71 /**
72 * @param object|string $docblock A string containing the DocBlock to parse or an object supporting the
73 * getDocComment method (such as a ReflectionClass object).
74 */
75 public function create($docblock, ?Types\Context $context = null, ?Location $location = null): DocBlock
76 {
77 if (is_object($docblock)) {
78 if (!method_exists($docblock, 'getDocComment')) {
79 $exceptionMessage = 'Invalid object passed; the given object must support the getDocComment method';
80
81 throw new InvalidArgumentException($exceptionMessage);
82 }
83
84 $docblock = $docblock->getDocComment();
85 Assert::string($docblock);
86 }
87
88 Assert::stringNotEmpty($docblock);
89
90 if ($context === null) {
91 $context = new Types\Context('');
92 }
93
94 $parts = $this->splitDocBlock($this->stripDocComment($docblock));
95
96 [$templateMarker, $summary, $description, $tags] = $parts;
97
98 return new DocBlock(
99 $summary,
100 $description ? $this->descriptionFactory->create($description, $context) : null,
101 $this->parseTagBlock($tags, $context),
102 $context,
103 $location,
104 $templateMarker === '#@+',
105 $templateMarker === '#@-'
106 );
107 }
108
109 /**
110 * @param class-string<Tag>|Factory $handler
111 */
112 public function registerTagHandler(string $tagName, $handler): void
113 {
114 $this->tagFactory->registerTagHandler($tagName, $handler);
115 }
116
117 /**
118 * Strips the asterisks from the DocBlock comment.
119 *
120 * @param string $comment String containing the comment text.
121 */
122 private function stripDocComment(string $comment): string
123 {
124 $comment = preg_replace('#[ \t]*(?:\/\*\*|\*\/|\*)?[ \t]?(.*)?#u', '$1', $comment);
125 Assert::string($comment);
126 $comment = trim($comment);
127
128 // reg ex above is not able to remove */ from a single line docblock
129 if (substr($comment, -2) === '*/') {
130 $comment = trim(substr($comment, 0, -2));
131 }
132
133 return str_replace(["\r\n", "\r"], "\n", $comment);
134 }
135
136 // phpcs:disable
137
138 /**
139 * Splits the DocBlock into a template marker, summary, description and block of tags.
140 *
141 * @param string $comment Comment to split into the sub-parts.
142 *
143 * @return string[] containing the template marker (if any), summary, description and a string containing the tags.
144 *
145 * @author Mike van Riel <[email protected]> for extending the regex with template marker support.
146 *
147 * @author Richard van Velzen (@_richardJ) Special thanks to Richard for the regex responsible for the split.
148 */
149 private function splitDocBlock(string $comment): array
150 {
151 // phpcs:enable
152 // Performance improvement cheat: if the first character is an @ then only tags are in this DocBlock. This
153 // method does not split tags so we return this verbatim as the fourth result (tags). This saves us the
154 // performance impact of running a regular expression
155 if (strpos($comment, '@') === 0) {
156 return ['', '', '', $comment];
157 }
158
159 // clears all extra horizontal whitespace from the line endings to prevent parsing issues
160 $comment = preg_replace('/\h*$/Sum', '', $comment);
161 Assert::string($comment);
162 /*
163 * Splits the docblock into a template marker, summary, description and tags section.
164 *
165 * - The template marker is empty, #@+ or #@- if the DocBlock starts with either of those (a newline may
166 * occur after it and will be stripped).
167 * - The short description is started from the first character until a dot is encountered followed by a
168 * newline OR two consecutive newlines (horizontal whitespace is taken into account to consider spacing
169 * errors). This is optional.
170 * - The long description, any character until a new line is encountered followed by an @ and word
171 * characters (a tag). This is optional.
172 * - Tags; the remaining characters
173 *
174 * Big thanks to RichardJ for contributing this Regular Expression
175 */
176 preg_match(
177 '/
178 \A
179 # 1. Extract the template marker
180 (?:(\#\@\+|\#\@\-)\n?)?
181
182 # 2. Extract the summary
183 (?:
184 (?! @\pL ) # The summary may not start with an @
185 (
186 [^\n.]+
187 (?:
188 (?! \. \n | \n{2} ) # End summary upon a dot followed by newline or two newlines
189 [\n.]* (?! [ \t]* @\pL ) # End summary when an @ is found as first character on a new line
190 [^\n.]+ # Include anything else
191 )*
192 \.?
193 )?
194 )
195
196 # 3. Extract the description
197 (?:
198 \s* # Some form of whitespace _must_ precede a description because a summary must be there
199 (?! @\pL ) # The description may not start with an @
200 (
201 [^\n]+
202 (?: \n+
203 (?! [ \t]* @\pL ) # End description when an @ is found as first character on a new line
204 [^\n]+ # Include anything else
205 )*
206 )
207 )?
208
209 # 4. Extract the tags (anything that follows)
210 (\s+ [\s\S]*)? # everything that follows
211 /ux',
212 $comment,
213 $matches
214 );
215 array_shift($matches);
216
217 while (count($matches) < 4) {
218 $matches[] = '';
219 }
220
221 return $matches;
222 }
223
224 /**
225 * Creates the tag objects.
226 *
227 * @param string $tags Tag block to parse.
228 * @param Types\Context $context Context of the parsed Tag
229 *
230 * @return DocBlock\Tag[]
231 */
232 private function parseTagBlock(string $tags, Types\Context $context): array
233 {
234 $tags = $this->filterTagBlock($tags);
235 if ($tags === null) {
236 return [];
237 }
238
239 $result = [];
240 $lines = $this->splitTagBlockIntoTagLines($tags);
241 foreach ($lines as $key => $tagLine) {
242 $result[$key] = $this->tagFactory->create(trim($tagLine), $context);
243 }
244
245 return $result;
246 }
247
248 /**
249 * @return string[]
250 */
251 private function splitTagBlockIntoTagLines(string $tags): array
252 {
253 $result = [];
254 foreach (explode("\n", $tags) as $tagLine) {
255 if ($tagLine !== '' && strpos($tagLine, '@') === 0) {
256 $result[] = $tagLine;
257 } else {
258 $result[count($result) - 1] .= "\n" . $tagLine;
259 }
260 }
261
262 return $result;
263 }
264
265 private function filterTagBlock(string $tags): ?string
266 {
267 $tags = trim($tags);
268 if (!$tags) {
269 return null;
270 }
271
272 if ($tags[0] !== '@') {
273 // @codeCoverageIgnoreStart
274 // Can't simulate this; this only happens if there is an error with the parsing of the DocBlock that
275 // we didn't foresee.
276
277 throw new LogicException('A tag block started with text instead of an at-sign(@): ' . $tags);
278
279 // @codeCoverageIgnoreEnd
280 }
281
282 return $tags;
283 }
284 }