Completed
Pull Request — master (#60)
by Greg
02:08
created

AbstractCommandDocBlockParser::getTagContents()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 1
1
<?php
2
namespace Consolidation\AnnotatedCommand\Parser\Internal;
3
4
use Consolidation\AnnotatedCommand\Parser\CommandInfo;
5
use Consolidation\AnnotatedCommand\Parser\DefaultsWithDescriptions;
6
7
/**
8
 * Given a class and method name, parse the annotations in the
9
 * DocBlock comment, and provide accessor methods for all of
10
 * the elements that are needed to create an annotated Command.
11
 */
12
abstract class AbstractCommandDocBlockParser
13
{
14
    /**
15
     * @var CommandInfo
16
     */
17
    protected $commandInfo;
18
19
    /**
20
     * @var \ReflectionMethod
21
     */
22
    protected $reflection;
23
24
    /**
25
     * @var array
26
     */
27
    protected $tagProcessors = [
28
        'command' => 'processCommandTag',
29
        'name' => 'processCommandTag',
30
        'arg' => 'processArgumentTag',
31
        'param' => 'processParamTag',
32
        'return' => 'processReturnTag',
33
        'option' => 'processOptionTag',
34
        'default' => 'processDefaultTag',
35
        'aliases' => 'processAliases',
36
        'usage' => 'processUsageTag',
37
        'topic' => 'processTopicTag',
38
        'description' => 'processAlternateDescriptionTag',
39
        'desc' => 'processAlternateDescriptionTag',
40
    ];
41
42
    public function __construct(CommandInfo $commandInfo, \ReflectionMethod $reflection)
43
    {
44
        $this->commandInfo = $commandInfo;
45
        $this->reflection = $reflection;
46
    }
47
48
    protected function processAllTags($phpdoc)
49
    {
50
        // Iterate over all of the tags, and process them as necessary.
51
        foreach ($phpdoc->getTags() as $tag) {
52
            $processFn = [$this, 'processGenericTag'];
53
            if (array_key_exists($tag->getName(), $this->tagProcessors)) {
54
                $processFn = [$this, $this->tagProcessors[$tag->getName()]];
55
            }
56
            $processFn($tag);
57
        }
58
    }
59
60
    abstract protected function getTagContents($tag);
61
62
    /**
63
     * Parse the docBlock comment for this command, and set the
64
     * fields of this class with the data thereby obtained.
65
     */
66
    abstract public function parse();
67
68
    /**
69
     * Save any tag that we do not explicitly recognize in the
70
     * 'otherAnnotations' map.
71
     */
72
    protected function processGenericTag($tag)
73
    {
74
        $this->commandInfo->addAnnotation($tag->getName(), $this->getTagContents($tag));
75
    }
76
77
    /**
78
     * Set the name of the command from a @command or @name annotation.
79
     */
80
    protected function processCommandTag($tag)
81
    {
82
        $commandName = $this->getTagContents($tag);
83
        $this->commandInfo->setName($commandName);
84
        // We also store the name in the 'other annotations' so that is is
85
        // possible to determine if the method had a @command annotation.
86
        $this->commandInfo->addAnnotation($tag->getName(), $commandName);
87
    }
88
89
    /**
90
     * The @description and @desc annotations may be used in
91
     * place of the synopsis (which we call 'description').
92
     * This is discouraged.
93
     *
94
     * @deprecated
95
     */
96
    protected function processAlternateDescriptionTag($tag)
97
    {
98
        $this->commandInfo->setDescription($this->getTagContents($tag));
99
    }
100
101
    /**
102
     * Store the data from a @arg annotation in our argument descriptions.
103
     */
104 View Code Duplication
    protected function processArgumentTag($tag)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
    {
106
        if (!$this->pregMatchNameAndDescription((string)$tag->getDescription(), $match)) {
107
            return;
108
        }
109
        $this->addOptionOrArgumentTag($tag, $this->commandInfo->arguments(), $match);
110
    }
111
112
    /**
113
     * Store the data from an @option annotation in our option descriptions.
114
     */
115
    protected function processOptionTag($tag)
116
    {
117
        if (!$this->pregMatchOptionNameAndDescription((string)$tag->getDescription(), $match)) {
118
            return;
119
        }
120
        $this->addOptionOrArgumentTag($tag, $this->commandInfo->options(), $match);
121
    }
122
123
    protected function addOptionOrArgumentTag($tag, DefaultsWithDescriptions $set, $nameAndDescription)
0 ignored issues
show
Unused Code introduced by
The parameter $tag is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
124
    {
125
        $variableName = $this->commandInfo->findMatchingOption($nameAndDescription['name']);
126
        $desc = $nameAndDescription['description'];
127
        $description = static::removeLineBreaks($desc);
128
        $set->add($variableName, $description);
129
    }
130
131
    /**
132
     * Store the data from a @default annotation in our argument or option store,
133
     * as appropriate.
134
     */
135
    protected function processDefaultTag($tag)
136
    {
137
        if (!$this->pregMatchNameAndDescription((string)$tag->getDescription(), $match)) {
138
            return;
139
        }
140
        $variableName = $match['name'];
141
        $defaultValue = $this->interpretDefaultValue($match['description']);
142
        if ($this->commandInfo->arguments()->exists($variableName)) {
143
            $this->commandInfo->arguments()->setDefaultValue($variableName, $defaultValue);
144
            return;
145
        }
146
        $variableName = $this->commandInfo->findMatchingOption($variableName);
147
        if ($this->commandInfo->options()->exists($variableName)) {
148
            $this->commandInfo->options()->setDefaultValue($variableName, $defaultValue);
149
        }
150
    }
151
152
    /**
153
     * Store the data from a @usage annotation in our example usage list.
154
     */
155 View Code Duplication
    protected function processUsageTag($tag)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
156
    {
157
        $lines = explode("\n", $this->getTagContents($tag));
158
        $usage = array_shift($lines);
159
        $description = static::removeLineBreaks(implode("\n", $lines));
160
161
        $this->commandInfo->setExampleUsage($usage, $description);
162
    }
163
164
    /**
165
     * Store the data from a @@topic annotation in our topics list.
166
     */
167 View Code Duplication
    protected function processTopicTag($tag)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
168
    {
169
        $lines = explode("\n", $this->getTagContents($tag));
170
        $topic = array_shift($lines);
171
        $description = static::removeLineBreaks(implode("\n", $lines));
172
173
        $this->commandInfo->setTopic($topic, $description);
174
    }
175
176
    /**
177
     * Process the comma-separated list of aliases
178
     */
179
    protected function processAliases($tag)
180
    {
181
        $this->commandInfo->setAliases((string)$tag->getDescription());
182
    }
183
184
    /**
185
     * Store the data from a @param annotation in our argument descriptions.
186
     */
187
    protected function processParamTag($tag)
188
    {
189
        $variableName = $tag->getVariableName();
190
        $variableName = str_replace('$', '', $variableName);
191
        $description = static::removeLineBreaks((string)$tag->getDescription());
192
        if ($variableName == $this->commandInfo->optionParamName()) {
193
            return;
194
        }
195
        $this->commandInfo->arguments()->add($variableName, $description);
196
    }
197
198
    /**
199
     * Store the data from a @return annotation in our argument descriptions.
200
     */
201
    abstract protected function processReturnTag($tag);
202
203
    protected function interpretDefaultValue($defaultValue)
204
    {
205
        $defaults = [
206
            'null' => null,
207
            'true' => true,
208
            'false' => false,
209
            "''" => '',
210
            '[]' => [],
211
        ];
212
        foreach ($defaults as $defaultName => $defaultTypedValue) {
213
            if ($defaultValue == $defaultName) {
214
                return $defaultTypedValue;
215
            }
216
        }
217
        return $defaultValue;
218
    }
219
220
    /**
221
     * Given a docblock description in the form "$variable description",
222
     * return the variable name and description via the 'match' parameter.
223
     */
224
    protected function pregMatchNameAndDescription($source, &$match)
225
    {
226
        $nameRegEx = '\\$(?P<name>[^ \t]+)[ \t]+';
227
        $descriptionRegEx = '(?P<description>.*)';
228
        $optionRegEx = "/{$nameRegEx}{$descriptionRegEx}/s";
229
230
        return preg_match($optionRegEx, $source, $match);
231
    }
232
233
    /**
234
     * Given a docblock description in the form "$variable description",
235
     * return the variable name and description via the 'match' parameter.
236
     */
237
    protected function pregMatchOptionNameAndDescription($source, &$match)
238
    {
239
        // Strip type and $ from the text before the @option name, if present.
240
        $source = preg_replace('/^[a-zA-Z]* ?\\$/', '', $source);
241
        $nameRegEx = '(?P<name>[^ \t]+)[ \t]+';
242
        $descriptionRegEx = '(?P<description>.*)';
243
        $optionRegEx = "/{$nameRegEx}{$descriptionRegEx}/s";
244
245
        return preg_match($optionRegEx, $source, $match);
246
    }
247
248
    /**
249
     * Given a list that might be 'a b c' or 'a, b, c' or 'a,b,c',
250
     * convert the data into the last of these forms.
251
     */
252
    protected static function convertListToCommaSeparated($text)
253
    {
254
        return preg_replace('#[ \t\n\r,]+#', ',', $text);
255
    }
256
257
    /**
258
     * Take a multiline description and convert it into a single
259
     * long unbroken line.
260
     */
261
    protected static function removeLineBreaks($text)
262
    {
263
        return trim(preg_replace('#[ \t\n\r]+#', ' ', $text));
264
    }
265
}
266