1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Console\Descriptor;
13
14use Symfony\Component\Console\Application;
15use Symfony\Component\Console\Command\Command;
16use Symfony\Component\Console\Formatter\OutputFormatter;
17use Symfony\Component\Console\Helper\Helper;
18use Symfony\Component\Console\Input\InputArgument;
19use Symfony\Component\Console\Input\InputDefinition;
20use Symfony\Component\Console\Input\InputOption;
21
22/**
23 * Text descriptor.
24 *
25 * @author Jean-François Simon <contact@jfsimon.fr>
26 *
27 * @internal
28 */
29class TextDescriptor extends Descriptor
30{
31    /**
32     * {@inheritdoc}
33     */
34    protected function describeInputArgument(InputArgument $argument, array $options = [])
35    {
36        if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) {
37            $default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($argument->getDefault()));
38        } else {
39            $default = '';
40        }
41
42        $totalWidth = isset($options['total_width']) ? $options['total_width'] : Helper::strlen($argument->getName());
43        $spacingWidth = $totalWidth - \strlen($argument->getName());
44
45        $this->writeText(sprintf('  <info>%s</info>  %s%s%s',
46            $argument->getName(),
47            str_repeat(' ', $spacingWidth),
48            // + 4 = 2 spaces before <info>, 2 spaces after </info>
49            preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $argument->getDescription()),
50            $default
51        ), $options);
52    }
53
54    /**
55     * {@inheritdoc}
56     */
57    protected function describeInputOption(InputOption $option, array $options = [])
58    {
59        if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) {
60            $default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($option->getDefault()));
61        } else {
62            $default = '';
63        }
64
65        $value = '';
66        if ($option->acceptValue()) {
67            $value = '='.strtoupper($option->getName());
68
69            if ($option->isValueOptional()) {
70                $value = '['.$value.']';
71            }
72        }
73
74        $totalWidth = isset($options['total_width']) ? $options['total_width'] : $this->calculateTotalWidthForOptions([$option]);
75        $synopsis = sprintf('%s%s',
76            $option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : '    ',
77            sprintf('--%s%s', $option->getName(), $value)
78        );
79
80        $spacingWidth = $totalWidth - Helper::strlen($synopsis);
81
82        $this->writeText(sprintf('  <info>%s</info>  %s%s%s%s',
83            $synopsis,
84            str_repeat(' ', $spacingWidth),
85            // + 4 = 2 spaces before <info>, 2 spaces after </info>
86            preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $option->getDescription()),
87            $default,
88            $option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''
89        ), $options);
90    }
91
92    /**
93     * {@inheritdoc}
94     */
95    protected function describeInputDefinition(InputDefinition $definition, array $options = [])
96    {
97        $totalWidth = $this->calculateTotalWidthForOptions($definition->getOptions());
98        foreach ($definition->getArguments() as $argument) {
99            $totalWidth = max($totalWidth, Helper::strlen($argument->getName()));
100        }
101
102        if ($definition->getArguments()) {
103            $this->writeText('<comment>Arguments:</comment>', $options);
104            $this->writeText("\n");
105            foreach ($definition->getArguments() as $argument) {
106                $this->describeInputArgument($argument, array_merge($options, ['total_width' => $totalWidth]));
107                $this->writeText("\n");
108            }
109        }
110
111        if ($definition->getArguments() && $definition->getOptions()) {
112            $this->writeText("\n");
113        }
114
115        if ($definition->getOptions()) {
116            $laterOptions = [];
117
118            $this->writeText('<comment>Options:</comment>', $options);
119            foreach ($definition->getOptions() as $option) {
120                if (\strlen($option->getShortcut()) > 1) {
121                    $laterOptions[] = $option;
122                    continue;
123                }
124                $this->writeText("\n");
125                $this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
126            }
127            foreach ($laterOptions as $option) {
128                $this->writeText("\n");
129                $this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
130            }
131        }
132    }
133
134    /**
135     * {@inheritdoc}
136     */
137    protected function describeCommand(Command $command, array $options = [])
138    {
139        $command->mergeApplicationDefinition(false);
140
141        if ($description = $command->getDescription()) {
142            $this->writeText('<comment>Description:</comment>', $options);
143            $this->writeText("\n");
144            $this->writeText('  '.$description);
145            $this->writeText("\n\n");
146        }
147
148        $this->writeText('<comment>Usage:</comment>', $options);
149        foreach (array_merge([$command->getSynopsis(true)], $command->getAliases(), $command->getUsages()) as $usage) {
150            $this->writeText("\n");
151            $this->writeText('  '.OutputFormatter::escape($usage), $options);
152        }
153        $this->writeText("\n");
154
155        $definition = $command->getDefinition();
156        if ($definition->getOptions() || $definition->getArguments()) {
157            $this->writeText("\n");
158            $this->describeInputDefinition($definition, $options);
159            $this->writeText("\n");
160        }
161
162        $help = $command->getProcessedHelp();
163        if ($help && $help !== $description) {
164            $this->writeText("\n");
165            $this->writeText('<comment>Help:</comment>', $options);
166            $this->writeText("\n");
167            $this->writeText('  '.str_replace("\n", "\n  ", $help), $options);
168            $this->writeText("\n");
169        }
170    }
171
172    /**
173     * {@inheritdoc}
174     */
175    protected function describeApplication(Application $application, array $options = [])
176    {
177        $describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
178        $description = new ApplicationDescription($application, $describedNamespace);
179
180        if (isset($options['raw_text']) && $options['raw_text']) {
181            $width = $this->getColumnWidth($description->getCommands());
182
183            foreach ($description->getCommands() as $command) {
184                $this->writeText(sprintf("%-{$width}s %s", $command->getName(), $command->getDescription()), $options);
185                $this->writeText("\n");
186            }
187        } else {
188            if ('' != $help = $application->getHelp()) {
189                $this->writeText("$help\n\n", $options);
190            }
191
192            $this->writeText("<comment>Usage:</comment>\n", $options);
193            $this->writeText("  command [options] [arguments]\n\n", $options);
194
195            $this->describeInputDefinition(new InputDefinition($application->getDefinition()->getOptions()), $options);
196
197            $this->writeText("\n");
198            $this->writeText("\n");
199
200            $commands = $description->getCommands();
201            $namespaces = $description->getNamespaces();
202            if ($describedNamespace && $namespaces) {
203                // make sure all alias commands are included when describing a specific namespace
204                $describedNamespaceInfo = reset($namespaces);
205                foreach ($describedNamespaceInfo['commands'] as $name) {
206                    $commands[$name] = $description->getCommand($name);
207                }
208            }
209
210            // calculate max. width based on available commands per namespace
211            $width = $this->getColumnWidth(array_merge(...array_values(array_map(function ($namespace) use ($commands) {
212                return array_intersect($namespace['commands'], array_keys($commands));
213            }, array_values($namespaces)))));
214
215            if ($describedNamespace) {
216                $this->writeText(sprintf('<comment>Available commands for the "%s" namespace:</comment>', $describedNamespace), $options);
217            } else {
218                $this->writeText('<comment>Available commands:</comment>', $options);
219            }
220
221            foreach ($namespaces as $namespace) {
222                $namespace['commands'] = array_filter($namespace['commands'], function ($name) use ($commands) {
223                    return isset($commands[$name]);
224                });
225
226                if (!$namespace['commands']) {
227                    continue;
228                }
229
230                if (!$describedNamespace && ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
231                    $this->writeText("\n");
232                    $this->writeText(' <comment>'.$namespace['id'].'</comment>', $options);
233                }
234
235                foreach ($namespace['commands'] as $name) {
236                    $this->writeText("\n");
237                    $spacingWidth = $width - Helper::strlen($name);
238                    $command = $commands[$name];
239                    $commandAliases = $name === $command->getName() ? $this->getCommandAliasesText($command) : '';
240                    $this->writeText(sprintf('  <info>%s</info>%s%s', $name, str_repeat(' ', $spacingWidth), $commandAliases.$command->getDescription()), $options);
241                }
242            }
243
244            $this->writeText("\n");
245        }
246    }
247
248    /**
249     * {@inheritdoc}
250     */
251    private function writeText(string $content, array $options = [])
252    {
253        $this->write(
254            isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content,
255            isset($options['raw_output']) ? !$options['raw_output'] : true
256        );
257    }
258
259    /**
260     * Formats command aliases to show them in the command description.
261     */
262    private function getCommandAliasesText(Command $command): string
263    {
264        $text = '';
265        $aliases = $command->getAliases();
266
267        if ($aliases) {
268            $text = '['.implode('|', $aliases).'] ';
269        }
270
271        return $text;
272    }
273
274    /**
275     * Formats input option/argument default value.
276     *
277     * @param mixed $default
278     */
279    private function formatDefaultValue($default): string
280    {
281        if (\INF === $default) {
282            return 'INF';
283        }
284
285        if (\is_string($default)) {
286            $default = OutputFormatter::escape($default);
287        } elseif (\is_array($default)) {
288            foreach ($default as $key => $value) {
289                if (\is_string($value)) {
290                    $default[$key] = OutputFormatter::escape($value);
291                }
292            }
293        }
294
295        return str_replace('\\\\', '\\', json_encode($default, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE));
296    }
297
298    /**
299     * @param (Command|string)[] $commands
300     */
301    private function getColumnWidth(array $commands): int
302    {
303        $widths = [];
304
305        foreach ($commands as $command) {
306            if ($command instanceof Command) {
307                $widths[] = Helper::strlen($command->getName());
308                foreach ($command->getAliases() as $alias) {
309                    $widths[] = Helper::strlen($alias);
310                }
311            } else {
312                $widths[] = Helper::strlen($command);
313            }
314        }
315
316        return $widths ? max($widths) + 2 : 0;
317    }
318
319    /**
320     * @param InputOption[] $options
321     */
322    private function calculateTotalWidthForOptions(array $options): int
323    {
324        $totalWidth = 0;
325        foreach ($options as $option) {
326            // "-" + shortcut + ", --" + name
327            $nameLength = 1 + max(Helper::strlen($option->getShortcut()), 1) + 4 + Helper::strlen($option->getName());
328
329            if ($option->acceptValue()) {
330                $valueLength = 1 + Helper::strlen($option->getName()); // = + value
331                $valueLength += $option->isValueOptional() ? 2 : 0; // [ + ]
332
333                $nameLength += $valueLength;
334            }
335            $totalWidth = max($totalWidth, $nameLength);
336        }
337
338        return $totalWidth;
339    }
340}
341