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

BespokeDocBlockParser::removeLineBreaks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
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
class BespokeDocBlockParser
13
{
14
    /**
15
     * @var array
16
     */
17
    protected $tagProcessors = [
18
        'command' => 'processCommandTag',
19
        'name' => 'processCommandTag',
20
        'arg' => 'processArgumentTag',
21
        'param' => 'processArgumentTag',
22
        'return' => 'processReturnTag',
23
        'option' => 'processOptionTag',
24
        'default' => 'processDefaultTag',
25
        'aliases' => 'processAliases',
26
        'usage' => 'processUsageTag',
27
        'description' => 'processAlternateDescriptionTag',
28
        'desc' => 'processAlternateDescriptionTag',
29
    ];
30
31
    public function __construct(CommandInfo $commandInfo, \ReflectionMethod $reflection)
32
    {
33
        $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...
34
        $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...
35
    }
36
37
    /**
38
     * Parse the docBlock comment for this command, and set the
39
     * fields of this class with the data thereby obtained.
40
     */
41
    public function parse()
42
    {
43
        $doc = $this->reflection->getDocComment();
44
        $this->parseDocBlock($doc);
45
    }
46
47
    /**
48
     * Save any tag that we do not explicitly recognize in the
49
     * 'otherAnnotations' map.
50
     */
51
    protected function processGenericTag($tag)
52
    {
53
        $this->commandInfo->addAnnotation($tag->getTag(), $tag->getContent());
54
    }
55
56
    /**
57
     * Set the name of the command from a @command or @name annotation.
58
     */
59
    protected function processCommandTag($tag)
60
    {
61
        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...
62
            throw new \Exception('Could not determine command name from tag ' . (string)$tag);
63
        }
64
        $commandName = $matches['word'];
65
        $this->commandInfo->setName($commandName);
66
        // We also store the name in the 'other annotations' so that is is
67
        // possible to determine if the method had a @command annotation.
68
        $this->commandInfo->addAnnotation($tag->getTag(), $commandName);
69
    }
70
71
    /**
72
     * The @description and @desc annotations may be used in
73
     * place of the synopsis (which we call 'description').
74
     * This is discouraged.
75
     *
76
     * @deprecated
77
     */
78
    protected function processAlternateDescriptionTag($tag)
79
    {
80
        $this->commandInfo->setDescription($tag->getContent());
81
    }
82
83
    /**
84
     * Store the data from a @arg annotation in our argument descriptions.
85
     */
86 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...
87
    {
88
        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...
89
            throw new \Exception('Could not determine parameter name from tag ' . (string)$tag);
90
        }
91
        if ($matches['variable'] == $this->optionParamName()) {
92
            return;
93
        }
94
        $this->addOptionOrArgumentTag($tag, $this->commandInfo->arguments(), $matches['variable'], $matches['description']);
95
    }
96
97
    /**
98
     * Store the data from an @option annotation in our option descriptions.
99
     */
100 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...
101
    {
102
        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...
103
            throw new \Exception('Could not determine parameter name from tag ' . (string)$tag);
104
        }
105
        $this->addOptionOrArgumentTag($tag, $this->commandInfo->options(), $matches['variable'], $matches['description']);
106
    }
107
108
    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...
109
    {
110
        $variableName = $this->commandInfo->findMatchingOption($name);
111
        $description = static::removeLineBreaks($description);
112
        $set->add($variableName, $description);
113
    }
114
115
    /**
116
     * Store the data from a @default annotation in our argument or option store,
117
     * as appropriate.
118
     */
119 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...
120
    {
121
        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...
122
            throw new \Exception('Could not determine parameter name from tag ' . (string)$tag);
123
        }
124
        $variableName = $matches['word'];
125
        $defaultValue = $this->interpretDefaultValue($matches['description']);
126
        if ($this->commandInfo->arguments()->exists($variableName)) {
127
            $this->commandInfo->arguments()->setDefaultValue($variableName, $defaultValue);
128
            return;
129
        }
130
        $variableName = $this->commandInfo->findMatchingOption($variableName);
131
        if ($this->commandInfo->options()->exists($variableName)) {
132
            $this->commandInfo->options()->setDefaultValue($variableName, $defaultValue);
133
        }
134
    }
135
136
    /**
137
     * Store the data from a @usage annotation in our example usage list.
138
     */
139
    protected function processUsageTag($tag)
140
    {
141
        $lines = explode("\n", $tag->getContent());
142
        $usage = trim(array_shift($lines));
143
        $description = static::removeLineBreaks(implode("\n", array_map(function ($line) {
144
            return trim($line);
145
        }, $lines)));
146
147
        $this->commandInfo->setExampleUsage($usage, $description);
148
    }
149
150
    /**
151
     * Process the comma-separated list of aliases
152
     */
153
    protected function processAliases($tag)
154
    {
155
        $this->commandInfo->setAliases((string)$tag->getContent());
156
    }
157
158
    /**
159
     * Store the data from a @return annotation in our argument descriptions.
160
     */
161
    protected function processReturnTag($tag)
162
    {
163
        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...
164
            throw new \Exception('Could not determine return type from tag ' . (string)$tag);
165
        }
166
        // TODO: look at namespace and `use` statments to make returnType a fqdn
167
        $returnType = $matches['word'];
168
        $this->commandInfo->setReturnType($returnType);
169
    }
170
171
    private function parseDocBlock($doc)
172
    {
173
        if (empty($doc)) {
174
            return;
175
        }
176
177
        $tagFactory = new TagFactory();
178
        $lines = [];
179
180
        foreach (explode("\n", $doc) as $row) {
181
            // Remove trailing whitespace and leading space + '*'s
182
            $row = rtrim($row);
183
            $row = preg_replace('#^[ \t]*\**#', '', $row);
184
185
            // Throw out the /** and */ lines ('*' trimmed from beginning)
186
            if ($row == '/**' || $row == '/') {
187
                continue;
188
            }
189
190
            if (!$tagFactory->parseLine($row)) {
191
                $lines[] = $row;
192
            }
193
        }
194
195
        $this->processDescriptionAndHelp($lines);
196
        $this->processAllTags($tagFactory->getTags());
197
    }
198
199
    protected function processDescriptionAndHelp($lines)
200
    {
201
        // Trim all of the lines individually.
202
        $lines =
203
            array_map(
204
                function ($line) {
205
                    return trim($line);
206
                },
207
                $lines
208
            );
209
210
        // Everything up to the first blank line goes in the description.
211
        $description = array_shift($lines);
212
        while ($this->nextLineIsNotEmpty($lines)) {
213
            $description .= ' ' . array_shift($lines);
214
        }
215
216
        // Everything else goes in the help.
217
        $help = trim(implode(PHP_EOL, $lines));
218
219
        $this->commandInfo->setDescription($description);
220
        $this->commandInfo->setHelp($help);
221
    }
222
223
    protected function nextLineIsNotEmpty($lines)
224
    {
225
        if (empty($lines)) {
226
            return false;
227
        }
228
229
        $nextLine = trim($lines[0]);
230
        return !empty($nextLine);
231
    }
232
233 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...
234
    {
235
        // Iterate over all of the tags, and process them as necessary.
236
        foreach ($tags as $tag) {
237
            $processFn = [$this, 'processGenericTag'];
238
            if (array_key_exists($tag->getTag(), $this->tagProcessors)) {
239
                $processFn = [$this, $this->tagProcessors[$tag->getTag()]];
240
            }
241
            $processFn($tag);
242
        }
243
    }
244
245 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...
246
    {
247
        $params = $this->commandInfo->getParameters();
248
        $param = end($params);
249
        if (!$param) {
250
            return '';
251
        }
252
        return $param->name;
253
    }
254
255
    /**
256
     * Return the name of the last parameter if it holds the options.
257
     */
258 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...
259
    {
260
        // Remember the name of the last parameter, if it holds the options.
261
        // We will use this information to ignore @param annotations for the options.
262
        if (!isset($this->optionParamName)) {
263
            $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...
264
            $options = $this->commandInfo->options();
265
            if (!$options->isEmpty()) {
266
                $this->optionParamName = $this->lastParameterName();
267
            }
268
        }
269
270
        return $this->optionParamName;
271
    }
272
273 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...
274
    {
275
        $defaults = [
276
            'null' => null,
277
            'true' => true,
278
            'false' => false,
279
            "''" => '',
280
            '[]' => [],
281
        ];
282
        foreach ($defaults as $defaultName => $defaultTypedValue) {
283
            if ($defaultValue == $defaultName) {
284
                return $defaultTypedValue;
285
            }
286
        }
287
        return $defaultValue;
288
    }
289
290
    /**
291
     * Given a list that might be 'a b c' or 'a, b, c' or 'a,b,c',
292
     * convert the data into the last of these forms.
293
     */
294
    protected static function convertListToCommaSeparated($text)
295
    {
296
        return preg_replace('#[ \t\n\r,]+#', ',', $text);
297
    }
298
299
    /**
300
     * Take a multiline description and convert it into a single
301
     * long unbroken line.
302
     */
303
    protected static function removeLineBreaks($text)
304
    {
305
        return trim(preg_replace('#[ \t\n\r]+#', ' ', $text));
306
    }
307
}
308