Debian Codegraph @

vendor/zircote/swagger-php/src/Analysers/DocBlockParser.php

raw
1 <?php declare(strict_types=1);
2
3 /**
4 * @license Apache 2.0
5 */
6
7 namespace OpenApi\Analysers;
8
9 use Doctrine\Common\Annotations\DocParser;
10 use OpenApi\Annotations as OA;
11 use OpenApi\Context;
12 use OpenApi\Generator;
13
14 /**
15 * Extract swagger-php annotations from a [PHPDoc](http://en.wikipedia.org/wiki/PHPDoc) using Doctrine's DocParser.
16 */
17 class DocBlockParser
18 {
19 protected DocParser $docParser;
20
21 /**
22 * @param array<string, class-string> $aliases
23 */
24 public function __construct(array $aliases = [])
25 {
26 if (DocBlockParser::isEnabled()) {
27 $docParser = new DocParser();
28 $docParser->setIgnoreNotImportedAnnotations(true);
29 $docParser->setImports($aliases);
30 $this->docParser = $docParser;
31 }
32 }
33
34 /**
35 * Check if we can process annotations.
36 */
37 public static function isEnabled(): bool
38 {
39 return class_exists('Doctrine\\Common\\Annotations\\DocParser');
40 }
41
42 /**
43 * @param array<string, class-string> $aliases
44 */
45 public function setAliases(array $aliases): void
46 {
47 $this->docParser->setImports($aliases);
48 }
49
50 /**
51 * Use doctrine to parse the comment block and return the detected annotations.
52 *
53 * @param string $comment a T_DOC_COMMENT
54 *
55 * @return list<OA\AbstractAnnotation|object>
56 */
57 public function fromComment(string $comment, Context $context): array
58 {
59 $context->comment = $comment;
60
61 try {
62 Generator::$context = $context;
63 if ($context->is('annotations') === false) {
64 $context->annotations = [];
65 }
66
67 return $this->docParser->parse($comment, $context->getDebugLocation());
68 } catch (\Exception $exception) {
69 if (preg_match('/^(.+) at position ([0-9]+) in ' . preg_quote((string) $context, '/') . '\.$/', $exception->getMessage(), $matches)) {
70 $errorMessage = $matches[1];
71 $errorPos = (int) $matches[2];
72 $atPos = strpos($comment, '@');
73 $context->line -= substr_count($comment, "\n", $atPos + $errorPos) + 1;
74 $lines = explode("\n", substr($comment, $atPos, $errorPos));
75 $context->character = strlen(array_pop($lines)) + 1; // position starts at 0 character starts at 1
76 $context->logger->error($errorMessage . ' in ' . $context, ['exception' => $exception]);
77 } else {
78 $context->logger->error(
79 $exception->getMessage() . ($context->filename ? ('; file=' . $context->filename) : ''),
80 ['exception' => $exception]
81 );
82 }
83
84 return [];
85 } finally {
86 Generator::$context = null;
87 }
88 }
89 }