@@ -179,6 +179,52 @@ will be autocompleted as the user types::
179179 $bundleName = $helper->ask($input, $output, $question);
180180 }
181181
182+ In more complex use cases, it may be necessary to generate suggestions on the
183+ fly, for instance if you wish to autocomplete a file path. In that case, you can
184+ provide a callback function to dynamically generate suggestions::
185+
186+ use Symfony\Component\Console\Question\Question;
187+
188+ // ...
189+ public function execute(InputInterface $input, OutputInterface $output)
190+ {
191+ // This function is called whenever the input changes and new
192+ // suggestions are needed.
193+ $callback = function (string $input): array {
194+ // Strip any characters from the last slash to the end of the
195+ // string - this is considered a complete path and should populate
196+ // our autocomplete suggestions.
197+ $inputPath = preg_replace(
198+ '%(/|^)[^/]*$%',
199+ '$1',
200+ $input
201+ );
202+
203+ // All suggestions should start with the input the user has already
204+ // provided (existing path), followed in this case by the contents
205+ // of the referenced directory. Some suggestions may be ignored
206+ // because they don't match the full string provided by the user,
207+ // but the autocomplete helper will take care of that for us.
208+ return array_map(
209+ function ($suggestion) use ($inputPath) {
210+ return $inputPath . $suggestion;
211+ },
212+ @scandir($inputPath === '' ? '.' : $inputPath) ?: []
213+ );
214+ };
215+
216+ $question = new Question('Please provide the full path of a file to parse');
217+ $question->setAutocompleterCallback($callback);
218+
219+ $filePath = $this->output->askQuestion($question);
220+ }
221+
222+ .. caution ::
223+
224+ This example code allows unrestricted access to the host filesystem, and
225+ should only ever be used in a local context, such as in a script being
226+ manually invoked from the command line on a server you control.
227+
182228Hiding the User's Response
183229~~~~~~~~~~~~~~~~~~~~~~~~~~
184230
0 commit comments