Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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
 
12
namespace Symfony\Component\Console\Command;
13
 
14
use Symfony\Component\Console\Attribute\AsCommand;
15
use Symfony\Component\Console\Completion\CompletionInput;
16
use Symfony\Component\Console\Completion\CompletionSuggestions;
17
use Symfony\Component\Console\Completion\Output\BashCompletionOutput;
18
use Symfony\Component\Console\Completion\Output\CompletionOutputInterface;
19
use Symfony\Component\Console\Completion\Output\FishCompletionOutput;
20
use Symfony\Component\Console\Completion\Output\ZshCompletionOutput;
21
use Symfony\Component\Console\Exception\CommandNotFoundException;
22
use Symfony\Component\Console\Exception\ExceptionInterface;
23
use Symfony\Component\Console\Input\InputInterface;
24
use Symfony\Component\Console\Input\InputOption;
25
use Symfony\Component\Console\Output\OutputInterface;
26
 
27
/**
28
 * Responsible for providing the values to the shell completion.
29
 *
30
 * @author Wouter de Jong <wouter@wouterj.nl>
31
 */
32
#[AsCommand(name: '|_complete', description: 'Internal command to provide shell completion suggestions')]
33
final class CompleteCommand extends Command
34
{
35
    public const COMPLETION_API_VERSION = '1';
36
 
37
    /**
38
     * @deprecated since Symfony 6.1
39
     */
40
    protected static $defaultName = '|_complete';
41
 
42
    /**
43
     * @deprecated since Symfony 6.1
44
     */
45
    protected static $defaultDescription = 'Internal command to provide shell completion suggestions';
46
 
47
    private $completionOutputs;
48
 
49
    private $isDebug = false;
50
 
51
    /**
52
     * @param array<string, class-string<CompletionOutputInterface>> $completionOutputs A list of additional completion outputs, with shell name as key and FQCN as value
53
     */
54
    public function __construct(array $completionOutputs = [])
55
    {
56
        // must be set before the parent constructor, as the property value is used in configure()
57
        $this->completionOutputs = $completionOutputs + [
58
            'bash' => BashCompletionOutput::class,
59
            'fish' => FishCompletionOutput::class,
60
            'zsh' => ZshCompletionOutput::class,
61
        ];
62
 
63
        parent::__construct();
64
    }
65
 
66
    protected function configure(): void
67
    {
68
        $this
69
            ->addOption('shell', 's', InputOption::VALUE_REQUIRED, 'The shell type ("'.implode('", "', array_keys($this->completionOutputs)).'")')
70
            ->addOption('input', 'i', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'An array of input tokens (e.g. COMP_WORDS or argv)')
71
            ->addOption('current', 'c', InputOption::VALUE_REQUIRED, 'The index of the "input" array that the cursor is in (e.g. COMP_CWORD)')
72
            ->addOption('api-version', 'a', InputOption::VALUE_REQUIRED, 'The API version of the completion script')
73
            ->addOption('symfony', 'S', InputOption::VALUE_REQUIRED, 'deprecated')
74
        ;
75
    }
76
 
77
    protected function initialize(InputInterface $input, OutputInterface $output)
78
    {
79
        $this->isDebug = filter_var(getenv('SYMFONY_COMPLETION_DEBUG'), \FILTER_VALIDATE_BOOL);
80
    }
81
 
82
    protected function execute(InputInterface $input, OutputInterface $output): int
83
    {
84
        try {
85
            // "symfony" must be kept for compat with the shell scripts generated by Symfony Console 5.4 - 6.1
86
            $version = $input->getOption('symfony') ? '1' : $input->getOption('api-version');
87
            if ($version && version_compare($version, self::COMPLETION_API_VERSION, '<')) {
88
                $message = sprintf('Completion script version is not supported ("%s" given, ">=%s" required).', $version, self::COMPLETION_API_VERSION);
89
                $this->log($message);
90
 
91
                $output->writeln($message.' Install the Symfony completion script again by using the "completion" command.');
92
 
93
                return 126;
94
            }
95
 
96
            $shell = $input->getOption('shell');
97
            if (!$shell) {
98
                throw new \RuntimeException('The "--shell" option must be set.');
99
            }
100
 
101
            if (!$completionOutput = $this->completionOutputs[$shell] ?? false) {
102
                throw new \RuntimeException(sprintf('Shell completion is not supported for your shell: "%s" (supported: "%s").', $shell, implode('", "', array_keys($this->completionOutputs))));
103
            }
104
 
105
            $completionInput = $this->createCompletionInput($input);
106
            $suggestions = new CompletionSuggestions();
107
 
108
            $this->log([
109
                '',
110
                '<comment>'.date('Y-m-d H:i:s').'</>',
111
                '<info>Input:</> <comment>("|" indicates the cursor position)</>',
112
                '  '.(string) $completionInput,
113
                '<info>Command:</>',
114
                '  '.(string) implode(' ', $_SERVER['argv']),
115
                '<info>Messages:</>',
116
            ]);
117
 
118
            $command = $this->findCommand($completionInput, $output);
119
            if (null === $command) {
120
                $this->log('  No command found, completing using the Application class.');
121
 
122
                $this->getApplication()->complete($completionInput, $suggestions);
123
            } elseif (
124
                $completionInput->mustSuggestArgumentValuesFor('command')
125
                && $command->getName() !== $completionInput->getCompletionValue()
126
                && !\in_array($completionInput->getCompletionValue(), $command->getAliases(), true)
127
            ) {
128
                $this->log('  No command found, completing using the Application class.');
129
 
130
                // expand shortcut names ("cache:cl<TAB>") into their full name ("cache:clear")
131
                $suggestions->suggestValues(array_filter(array_merge([$command->getName()], $command->getAliases())));
132
            } else {
133
                $command->mergeApplicationDefinition();
134
                $completionInput->bind($command->getDefinition());
135
 
136
                if (CompletionInput::TYPE_OPTION_NAME === $completionInput->getCompletionType()) {
137
                    $this->log('  Completing option names for the <comment>'.\get_class($command instanceof LazyCommand ? $command->getCommand() : $command).'</> command.');
138
 
139
                    $suggestions->suggestOptions($command->getDefinition()->getOptions());
140
                } else {
141
                    $this->log([
142
                        '  Completing using the <comment>'.\get_class($command instanceof LazyCommand ? $command->getCommand() : $command).'</> class.',
143
                        '  Completing <comment>'.$completionInput->getCompletionType().'</> for <comment>'.$completionInput->getCompletionName().'</>',
144
                    ]);
145
                    if (null !== $compval = $completionInput->getCompletionValue()) {
146
                        $this->log('  Current value: <comment>'.$compval.'</>');
147
                    }
148
 
149
                    $command->complete($completionInput, $suggestions);
150
                }
151
            }
152
 
153
            /** @var CompletionOutputInterface $completionOutput */
154
            $completionOutput = new $completionOutput();
155
 
156
            $this->log('<info>Suggestions:</>');
157
            if ($options = $suggestions->getOptionSuggestions()) {
158
                $this->log('  --'.implode(' --', array_map(function ($o) { return $o->getName(); }, $options)));
159
            } elseif ($values = $suggestions->getValueSuggestions()) {
160
                $this->log('  '.implode(' ', $values));
161
            } else {
162
                $this->log('  <comment>No suggestions were provided</>');
163
            }
164
 
165
            $completionOutput->write($suggestions, $output);
166
        } catch (\Throwable $e) {
167
            $this->log([
168
                '<error>Error!</error>',
169
                (string) $e,
170
            ]);
171
 
172
            if ($output->isDebug()) {
173
                throw $e;
174
            }
175
 
176
            return self::FAILURE;
177
        }
178
 
179
        return self::SUCCESS;
180
    }
181
 
182
    private function createCompletionInput(InputInterface $input): CompletionInput
183
    {
184
        $currentIndex = $input->getOption('current');
185
        if (!$currentIndex || !ctype_digit($currentIndex)) {
186
            throw new \RuntimeException('The "--current" option must be set and it must be an integer.');
187
        }
188
 
189
        $completionInput = CompletionInput::fromTokens($input->getOption('input'), (int) $currentIndex);
190
 
191
        try {
192
            $completionInput->bind($this->getApplication()->getDefinition());
193
        } catch (ExceptionInterface) {
194
        }
195
 
196
        return $completionInput;
197
    }
198
 
199
    private function findCommand(CompletionInput $completionInput, OutputInterface $output): ?Command
200
    {
201
        try {
202
            $inputName = $completionInput->getFirstArgument();
203
            if (null === $inputName) {
204
                return null;
205
            }
206
 
207
            return $this->getApplication()->find($inputName);
208
        } catch (CommandNotFoundException) {
209
        }
210
 
211
        return null;
212
    }
213
 
214
    private function log($messages): void
215
    {
216
        if (!$this->isDebug) {
217
            return;
218
        }
219
 
220
        $commandName = basename($_SERVER['argv'][0]);
221
        file_put_contents(sys_get_temp_dir().'/sf_'.$commandName.'.log', implode(\PHP_EOL, (array) $messages).\PHP_EOL, \FILE_APPEND);
222
    }
223
}