xref: /dokuwiki/inc/Remote/OpenApiDoc/DocBlock.php (revision 6cce3332fbc12c1e250ec7e6adbad6d4dc2c74e8)
1<?php
2
3namespace dokuwiki\Remote\OpenApiDoc;
4
5use Reflector;
6
7class DocBlock
8{
9    /** @var Reflector The reflected object */
10    protected $reflector;
11
12    /** @var string The first line of the decription */
13    protected $summary = '';
14
15    /** @var string The description */
16    protected $description = '';
17
18    /** @var string The parsed tags */
19    protected $tags = [];
20
21    /**
22     * Parse the given docblock
23     *
24     * The docblock can be of a method, class or property.
25     *
26     * @param Reflector $reflector
27     */
28    public function __construct(Reflector $reflector)
29    {
30        $this->reflector = $reflector;
31        $docblock = $reflector->getDocComment();
32
33        // strip asterisks and leading spaces
34        $docblock = trim(preg_replace(
35            ['/^[ \t]*\/\*+[ \t]*/m', '/[ \t]*\*+[ \t]*/m', '/\*+\/\s*$/m', '/\s*\/\s*$/m'],
36            ['', '', '', ''],
37            $docblock
38        ));
39
40        // get all tags
41        $tags = [];
42        if (preg_match_all('/^@(\w+)\s+(.*)$/m', $docblock, $matches, PREG_SET_ORDER)) {
43            foreach ($matches as $match) {
44                $tags[$match[1]][] = trim($match[2]);
45            }
46        }
47
48        // strip the tags from the docblock
49        $docblock = preg_replace('/^@(\w+)\s+(.*)$/m', '', $docblock);
50
51        // what remains is summary and description
52        [$summary, $description] = sexplode("\n\n", $docblock, 2, '');
53
54        // store everything
55        $this->summary = trim($summary);
56        $this->description = trim($description);
57        $this->tags = $tags;
58    }
59
60    /**
61     * The class name of the declaring class
62     *
63     * @return string
64     */
65    protected function getContext()
66    {
67        return $this->reflector->getDeclaringClass()->getName();
68    }
69
70    /**
71     * @return string
72     */
73    public function getSummary(): string
74    {
75        return $this->summary;
76    }
77
78    /**
79     * @return string
80     */
81    public function getDescription(): string
82    {
83        return $this->description;
84    }
85
86    /**
87     * Get all tags
88     *
89     * @return array
90     */
91    public function getTags()
92    {
93        return $this->tags;
94    }
95
96    /**
97     * Get a specific tag
98     *
99     * @param string $tag
100     * @return array
101     */
102    public function getTag($tag)
103    {
104        if (!isset($this->tags[$tag])) return [];
105        return $this->tags[$tag];
106    }
107}
108