Completed
Pull Request — master (#65)
by
unknown
04:30
created

AbstractCommandDocBlockParser::processUsageTag()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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