CommandHelp::renderHelp()   C
last analyzed

Complexity

Conditions 7
Paths 32

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 28
ccs 16
cts 16
cp 1
rs 6.7272
cc 7
eloc 15
nc 32
nop 1
crap 7
1
<?php
2
3
/*
4
 * This file is part of the webmozart/console package.
5
 *
6
 * (c) Bernhard Schussek <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Webmozart\Console\UI\Help;
13
14
use Webmozart\Console\Api\Args\Format\Argument;
15
use Webmozart\Console\Api\Args\Format\Option;
16
use Webmozart\Console\Api\Command\Command;
17
use Webmozart\Console\Api\Command\CommandCollection;
18
use Webmozart\Console\Api\Config\OptionCommandConfig;
19
use Webmozart\Console\UI\Component\EmptyLine;
20
use Webmozart\Console\UI\Component\Paragraph;
21
use Webmozart\Console\UI\Layout\BlockLayout;
22
23
/**
24
 * Renders the help of a console command.
25
 *
26
 * @since  1.0
27
 *
28
 * @author Bernhard Schussek <[email protected]>
29
 */
30
class CommandHelp extends AbstractHelp
31
{
32
    /**
33
     * @var Command
34
     */
35
    private $command;
36
37
    /**
38
     * Creates the help.
39
     *
40
     * @param Command $command The command to render.
41
     */
42 27
    public function __construct(Command $command)
43
    {
44 27
        $this->command = $command;
45 27
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 27
    protected function renderHelp(BlockLayout $layout)
51
    {
52 27
        $help = $this->command->getConfig()->getHelp();
53 27
        $argsFormat = $this->command->getArgsFormat();
54 27
        $subCommands = $this->command->getNamedSubCommands();
55
56 27
        $this->renderUsage($layout, $this->command);
57
58 27
        if ($argsFormat->hasArguments()) {
59 4
            $this->renderArguments($layout, $argsFormat->getArguments());
60
        }
61
62 27
        if (!$subCommands->isEmpty()) {
63 8
            $this->renderSubCommands($layout, $subCommands);
64
        }
65
66 27
        if ($argsFormat->hasOptions(false)) {
67 9
            $this->renderOptions($layout, $argsFormat->getOptions(false));
68
        }
69
70 27
        if ($argsFormat->getBaseFormat() && $argsFormat->getBaseFormat()->hasOptions()) {
71 14
            $this->renderGlobalOptions($layout, $argsFormat->getBaseFormat()->getOptions());
72
        }
73
74 27
        if ($help) {
75 1
            $this->renderDescription($layout, $help);
76
        }
77 27
    }
78
79
    /**
80
     * Renders the "Usage" section.
81
     *
82
     * @param BlockLayout $layout  The layout.
83
     * @param Command     $command The command to render.
84
     */
85 27
    protected function renderUsage(BlockLayout $layout, Command $command)
86
    {
87 27
        $formatsToPrint = array();
88
89
        // Start with the default commands
90 27
        if ($command->hasDefaultSubCommands()) {
91
            // If the command has default commands, print them
92 4
            foreach ($command->getDefaultSubCommands() as $subCommand) {
93
                // The name of the sub command is only optional (i.e. printed
94
                // wrapped in brackets: "[sub]") if the command is not
95
                // anonymous
96 4
                $nameOptional = !$subCommand->getConfig()->isAnonymous();
97
98 4
                $formatsToPrint[] = array($subCommand->getArgsFormat(), $nameOptional);
99
            }
100
        } else {
101
            // Otherwise print the command's usage itself
102 23
            $formatsToPrint[] = array($command->getArgsFormat(), false);
103
        }
104
105
        // Add remaining sub-commands
106 27
        foreach ($command->getSubCommands() as $subCommand) {
107
            // Don't duplicate default commands
108 8
            if (!$subCommand->getConfig()->isDefault()) {
109 8
                $formatsToPrint[$subCommand->getName()] = array($subCommand->getArgsFormat(), false);
110
            }
111
        }
112
113 27
        $appName = $command->getApplication()->getConfig()->getName();
114 27
        $prefix = count($formatsToPrint) > 1 ? '    ' : '';
115
116 27
        $layout->add(new Paragraph('<b>USAGE</b>'));
117 27
        $layout->beginBlock();
118
119 27
        foreach ($formatsToPrint as $vars) {
120 27
            $this->renderSynopsis($layout, $vars[0], $appName, $prefix, $vars[1]);
121 27
            $prefix = 'or: ';
122
        }
123
124 27
        if ($command->hasAliases()) {
125 1
            $layout->add(new EmptyLine());
126 1
            $this->renderAliases($layout, $command->getAliases());
127
        }
128
129 27
        $layout->endBlock();
130 27
        $layout->add(new EmptyLine());
131 27
    }
132
133
    /**
134
     * Renders the aliases of a command.
135
     *
136
     * @param BlockLayout $layout  The layout.
137
     * @param string[]    $aliases The aliases to render.
138
     */
139 1
    protected function renderAliases(BlockLayout $layout, $aliases)
140
    {
141 1
        $layout->add(new Paragraph('aliases: '.implode(', ', $aliases)));
142 1
    }
143
144
    /**
145
     * Renders the "Commands" section.
146
     *
147
     * @param BlockLayout       $layout      The layout.
148
     * @param CommandCollection $subCommands The sub-commands to render.
149
     */
150 8 View Code Duplication
    protected function renderSubCommands(BlockLayout $layout, CommandCollection $subCommands)
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...
151
    {
152 8
        $layout->add(new Paragraph('<b>COMMANDS</b>'));
153 8
        $layout->beginBlock();
154
155 8
        $subCommands = $subCommands->toArray();
156 8
        ksort($subCommands);
157
158 8
        foreach ($subCommands as $subCommand) {
159 8
            $this->renderSubCommand($layout, $subCommand);
160
        }
161
162 8
        $layout->endBlock();
163 8
    }
164
165
    /**
166
     * Renders a sub-command in the "Commands" section.
167
     *
168
     * @param BlockLayout $layout  The layout.
169
     * @param Command     $command The command to render.
170
     */
171 8
    protected function renderSubCommand(BlockLayout $layout, Command $command)
172
    {
173 8
        $config = $command->getConfig();
174 8
        $description = $config->getDescription();
175 8
        $help = $config->getHelp();
176 8
        $arguments = $command->getArgsFormat()->getArguments(false);
177 8
        $options = $command->getArgsFormat()->getOptions(false);
178
179 8
        if ($config instanceof OptionCommandConfig) {
180 4
            if ($config->isLongNamePreferred()) {
181 4
                $preferredName = '--<u>'.$config->getLongName().'</u>';
182 4
                $alternativeName = $config->getShortName() ? '-<u>'.$config->getShortName().'</u>' : null;
183
            } else {
184 2
                $preferredName = '-<u>'.$config->getShortName().'</u>';
185 2
                $alternativeName = '--<u>'.$config->getLongName().'</u>';
186
            }
187
188 4
            $name = $preferredName;
189
190 4
            if ($alternativeName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $alternativeName of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
191 4
                $name .= ' ('.$alternativeName.')';
192
            }
193
        } else {
194 4
            $name = '<u>'.$command->getName().'</u>';
195
        }
196
197 8
        $layout->add(new Paragraph($name));
198 8
        $layout->beginBlock();
199
200 8
        if ($description) {
201 7
            $this->renderSubCommandDescription($layout, $description);
202
        }
203
204 8
        if ($help) {
205
            $this->renderSubCommandHelp($layout, $help);
206
        }
207
208 8
        if ($arguments) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $arguments of type Webmozart\Console\Api\Args\Format\Argument[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
209 4
            $this->renderSubCommandArguments($layout, $arguments);
210
        }
211
212 8
        if ($options) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $options of type Webmozart\Console\Api\Args\Format\Option[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
213 2
            $this->renderSubCommandOptions($layout, $options);
214
        }
215
216 8
        if (!$description && !$help && !$arguments && !$options) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $arguments of type Webmozart\Console\Api\Args\Format\Argument[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
Bug Best Practice introduced by
The expression $options of type Webmozart\Console\Api\Args\Format\Option[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
217 1
            $layout->add(new EmptyLine());
218
        }
219
220 8
        $layout->endBlock();
221 8
    }
222
223
    /**
224
     * Renders the description of a sub-command.
225
     *
226
     * @param BlockLayout $layout      The layout.
227
     * @param string      $description The description.
228
     */
229 7
    protected function renderSubCommandDescription(BlockLayout $layout, $description)
230
    {
231 7
        $layout->add(new Paragraph($description));
232 7
        $layout->add(new EmptyLine());
233 7
    }
234
235
    /**
236
     * Renders the help text of a sub-command.
237
     *
238
     * @param BlockLayout $layout The layout.
239
     * @param string      $help   The help text.
240
     */
241
    protected function renderSubCommandHelp(BlockLayout $layout, $help)
242
    {
243
        $layout->add(new Paragraph($help));
244
        $layout->add(new EmptyLine());
245
    }
246
247
    /**
248
     * Renders the argument descriptions of a sub-command.
249
     *
250
     * @param BlockLayout $layout    The layout.
251
     * @param Argument[]  $arguments The arguments.
252
     */
253 4
    protected function renderSubCommandArguments(BlockLayout $layout, array $arguments)
254
    {
255 4
        foreach ($arguments as $argument) {
256 4
            $this->renderArgument($layout, $argument);
257
        }
258
259 4
        $layout->add(new EmptyLine());
260 4
    }
261
262
    /**
263
     * Renders the option descriptions of a sub-command.
264
     *
265
     * @param BlockLayout $layout  The layout.
266
     * @param Option[]    $options The options.
267
     */
268 2
    protected function renderSubCommandOptions(BlockLayout $layout, array $options)
269
    {
270 2
        foreach ($options as $option) {
271 2
            $this->renderOption($layout, $option);
272
        }
273
274 2
        $layout->add(new EmptyLine());
275 2
    }
276
277
    /**
278
     * Renders the "Description" section.
279
     *
280
     * @param BlockLayout $layout The layout.
281
     * @param string      $help   The help text.
282
     */
283 1
    protected function renderDescription(BlockLayout $layout, $help)
284
    {
285
        $layout
286 1
            ->add(new Paragraph('<b>DESCRIPTION</b>'))
287 1
            ->beginBlock()
288 1
            ->add(new Paragraph($help))
289 1
            ->endBlock()
290 1
            ->add(new EmptyLine())
291
        ;
292 1
    }
293
}
294