Completed
Pull Request — master (#130)
by Greg
01:45
created

BespokeDocBlockParser::findFullyQualifiedClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
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
class BespokeDocBlockParser
13
{
14
    protected $fqcnCache;
15
16
    /**
17
     * @var array
18
     */
19
    protected $tagProcessors = [
20
        'command' => 'processCommandTag',
21
        'name' => 'processCommandTag',
22
        'arg' => 'processArgumentTag',
23
        'param' => 'processArgumentTag',
24
        'return' => 'processReturnTag',
25
        'option' => 'processOptionTag',
26
        'default' => 'processDefaultTag',
27
        'aliases' => 'processAliases',
28
        'usage' => 'processUsageTag',
29
        'description' => 'processAlternateDescriptionTag',
30
        'desc' => 'processAlternateDescriptionTag',
31
    ];
32
33
    public function __construct(CommandInfo $commandInfo, \ReflectionMethod $reflection, $fqcnCache = null)
34
    {
35
        $this->commandInfo = $commandInfo;
0 ignored issues
show
Bug introduced by
The property commandInfo does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
36
        $this->reflection = $reflection;
0 ignored issues
show
Bug introduced by
The property reflection does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
37
        $this->fqcnCache = $fqcnCache ?: new FullyQualifiedClassCache();
38
    }
39
40
    /**
41
     * Parse the docBlock comment for this command, and set the
42
     * fields of this class with the data thereby obtained.
43
     */
44
    public function parse()
45
    {
46
        $doc = $this->reflection->getDocComment();
47
        $this->parseDocBlock($doc);
48
    }
49
50
    /**
51
     * Save any tag that we do not explicitly recognize in the
52
     * 'otherAnnotations' map.
53
     */
54
    protected function processGenericTag($tag)
55
    {
56
        $this->commandInfo->addAnnotation($tag->getTag(), $tag->getContent());
57
    }
58
59
    /**
60
     * Set the name of the command from a @command or @name annotation.
61
     */
62 View Code Duplication
    protected function processCommandTag($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...
63
    {
64
        if (!$tag->hasWordAndDescription($matches)) {
0 ignored issues
show
Bug introduced by
The variable $matches does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
65
            throw new \Exception('Could not determine command name from tag ' . (string)$tag);
66
        }
67
        $commandName = $matches['word'];
68
        $this->commandInfo->setName($commandName);
69
        // We also store the name in the 'other annotations' so that is is
70
        // possible to determine if the method had a @command annotation.
71
        $this->commandInfo->addAnnotation($tag->getTag(), $commandName);
72
    }
73
74
    /**
75
     * The @description and @desc annotations may be used in
76
     * place of the synopsis (which we call 'description').
77
     * This is discouraged.
78
     *
79
     * @deprecated
80
     */
81
    protected function processAlternateDescriptionTag($tag)
82
    {
83
        $this->commandInfo->setDescription($tag->getContent());
84
    }
85
86
    /**
87
     * Store the data from a @arg annotation in our argument descriptions.
88
     */
89 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...
90
    {
91
        if (!$tag->hasVariable($matches)) {
0 ignored issues
show
Bug introduced by
The variable $matches does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
92
            throw new \Exception('Could not determine parameter name from tag ' . (string)$tag);
93
        }
94
        if ($matches['variable'] == $this->optionParamName()) {
95
            return;
96
        }
97
        $this->addOptionOrArgumentTag($tag, $this->commandInfo->arguments(), $matches['variable'], $matches['description']);
98
    }
99
100
    /**
101
     * Store the data from an @option annotation in our option descriptions.
102
     */
103 View Code Duplication
    protected function processOptionTag($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...
104
    {
105
        if (!$tag->hasVariable($matches)) {
0 ignored issues
show
Bug introduced by
The variable $matches does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
106
            throw new \Exception('Could not determine parameter name from tag ' . (string)$tag);
107
        }
108
        $this->addOptionOrArgumentTag($tag, $this->commandInfo->options(), $matches['variable'], $matches['description']);
109
    }
110
111
    protected function addOptionOrArgumentTag($tag, DefaultsWithDescriptions $set, $name, $description)
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...
112
    {
113
        $variableName = $this->commandInfo->findMatchingOption($name);
114
        $description = static::removeLineBreaks($description);
115
        $set->add($variableName, $description);
116
    }
117
118
    /**
119
     * Store the data from a @default annotation in our argument or option store,
120
     * as appropriate.
121
     */
122 View Code Duplication
    protected function processDefaultTag($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...
123
    {
124
        if (!$tag->hasWordAndDescription($matches)) {
0 ignored issues
show
Bug introduced by
The variable $matches does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
125
            throw new \Exception('Could not determine parameter name from tag ' . (string)$tag);
126
        }
127
        $variableName = $matches['word'];
128
        $defaultValue = $this->interpretDefaultValue($matches['description']);
129
        if ($this->commandInfo->arguments()->exists($variableName)) {
130
            $this->commandInfo->arguments()->setDefaultValue($variableName, $defaultValue);
131
            return;
132
        }
133
        $variableName = $this->commandInfo->findMatchingOption($variableName);
134
        if ($this->commandInfo->options()->exists($variableName)) {
135
            $this->commandInfo->options()->setDefaultValue($variableName, $defaultValue);
136
        }
137
    }
138
139
    /**
140
     * Store the data from a @usage annotation in our example usage list.
141
     */
142
    protected function processUsageTag($tag)
143
    {
144
        $lines = explode("\n", $tag->getContent());
145
        $usage = trim(array_shift($lines));
146
        $description = static::removeLineBreaks(implode("\n", array_map(function ($line) {
147
            return trim($line);
148
        }, $lines)));
149
150
        $this->commandInfo->setExampleUsage($usage, $description);
151
    }
152
153
    /**
154
     * Process the comma-separated list of aliases
155
     */
156
    protected function processAliases($tag)
157
    {
158
        $this->commandInfo->setAliases((string)$tag->getContent());
159
    }
160
161
    /**
162
     * Store the data from a @return annotation in our argument descriptions.
163
     */
164 View Code Duplication
    protected function processReturnTag($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...
165
    {
166
        if (!$tag->hasWordAndDescription($matches)) {
0 ignored issues
show
Bug introduced by
The variable $matches does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
167
            throw new \Exception('Could not determine return type from tag ' . (string)$tag);
168
        }
169
        // Look at namespace and `use` statments to make returnType a fqdn
170
        $returnType = $matches['word'];
171
        $returnType = $this->findFullyQualifiedClass($returnType);
172
        $this->commandInfo->setReturnType($returnType);
173
    }
174
175
    protected function findFullyQualifiedClass($className)
176
    {
177
        if (strpos($className, '\\') !== false) {
178
            return $className;
179
        }
180
181
        return $this->fqcnCache->qualify($this->reflection->getFileName(), $className);
182
    }
183
184
    private function parseDocBlock($doc)
185
    {
186
        if (empty($doc)) {
187
            return;
188
        }
189
190
        $tagFactory = new TagFactory();
191
        $lines = [];
192
193
        foreach (explode("\n", $doc) as $row) {
194
            // Remove trailing whitespace and leading space + '*'s
195
            $row = rtrim($row);
196
            $row = preg_replace('#^[ \t]*\**#', '', $row);
197
198
            // Throw out the /** and */ lines ('*' trimmed from beginning)
199
            if ($row == '/**' || $row == '/') {
200
                continue;
201
            }
202
203
            if (!$tagFactory->parseLine($row)) {
204
                $lines[] = $row;
205
            }
206
        }
207
208
        $this->processDescriptionAndHelp($lines);
209
        $this->processAllTags($tagFactory->getTags());
210
    }
211
212
    protected function processDescriptionAndHelp($lines)
213
    {
214
        // Trim all of the lines individually.
215
        $lines =
216
            array_map(
217
                function ($line) {
218
                    return trim($line);
219
                },
220
                $lines
221
            );
222
223
        // Everything up to the first blank line goes in the description.
224
        $description = array_shift($lines);
225
        while ($this->nextLineIsNotEmpty($lines)) {
226
            $description .= ' ' . array_shift($lines);
227
        }
228
229
        // Everything else goes in the help.
230
        $help = trim(implode(PHP_EOL, $lines));
231
232
        $this->commandInfo->setDescription($description);
233
        $this->commandInfo->setHelp($help);
234
    }
235
236
    protected function nextLineIsNotEmpty($lines)
237
    {
238
        if (empty($lines)) {
239
            return false;
240
        }
241
242
        $nextLine = trim($lines[0]);
243
        return !empty($nextLine);
244
    }
245
246 View Code Duplication
    protected function processAllTags($tags)
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...
247
    {
248
        // Iterate over all of the tags, and process them as necessary.
249
        foreach ($tags as $tag) {
250
            $processFn = [$this, 'processGenericTag'];
251
            if (array_key_exists($tag->getTag(), $this->tagProcessors)) {
252
                $processFn = [$this, $this->tagProcessors[$tag->getTag()]];
253
            }
254
            $processFn($tag);
255
        }
256
    }
257
258 View Code Duplication
    protected function lastParameterName()
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...
259
    {
260
        $params = $this->commandInfo->getParameters();
261
        $param = end($params);
262
        if (!$param) {
263
            return '';
264
        }
265
        return $param->name;
266
    }
267
268
    /**
269
     * Return the name of the last parameter if it holds the options.
270
     */
271 View Code Duplication
    public function optionParamName()
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...
272
    {
273
        // Remember the name of the last parameter, if it holds the options.
274
        // We will use this information to ignore @param annotations for the options.
275
        if (!isset($this->optionParamName)) {
276
            $this->optionParamName = '';
0 ignored issues
show
Bug introduced by
The property optionParamName does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
277
            $options = $this->commandInfo->options();
278
            if (!$options->isEmpty()) {
279
                $this->optionParamName = $this->lastParameterName();
280
            }
281
        }
282
283
        return $this->optionParamName;
284
    }
285
286 View Code Duplication
    protected function interpretDefaultValue($defaultValue)
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...
287
    {
288
        $defaults = [
289
            'null' => null,
290
            'true' => true,
291
            'false' => false,
292
            "''" => '',
293
            '[]' => [],
294
        ];
295
        foreach ($defaults as $defaultName => $defaultTypedValue) {
296
            if ($defaultValue == $defaultName) {
297
                return $defaultTypedValue;
298
            }
299
        }
300
        return $defaultValue;
301
    }
302
303
    /**
304
     * Given a list that might be 'a b c' or 'a, b, c' or 'a,b,c',
305
     * convert the data into the last of these forms.
306
     */
307
    protected static function convertListToCommaSeparated($text)
308
    {
309
        return preg_replace('#[ \t\n\r,]+#', ',', $text);
310
    }
311
312
    /**
313
     * Take a multiline description and convert it into a single
314
     * long unbroken line.
315
     */
316
    protected static function removeLineBreaks($text)
317
    {
318
        return trim(preg_replace('#[ \t\n\r]+#', ' ', $text));
319
    }
320
}
321