8000 [Console] Add callback support to Console\Question autocompleter by MikkelPaulson · Pull Request #30997 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Console] Add callback support to Console\Question autocompleter #30997

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Symfony/Component/Console/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ CHANGELOG

* added support for hyperlinks
* added `ProgressBar::iterate()` method that simplify updating the progress bar when iterating
* added `Question::setAutocompleterCallback()` to provide a callback function
that dynamically generates suggestions as the user types

4.2.0
-----
Expand Down
29 changes: 17 additions & 12 deletions src/Symfony/Component/Console/Helper/QuestionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ private function doAsk(OutputInterface $output, Question $question)
$this->writePrompt($output, $question);

$inputStream = $this->inputStream ?: STDIN;
$autocomplete = $question->getAutocompleterValues();
$autocomplete = $question->getAutocompleterCallback();

if (null === $autocomplete || !$this->hasSttyAvailable()) {
$ret = false;
Expand All @@ -137,7 +137,7 @@ private function doAsk(OutputInterface $output, Question $question)
$ret = trim($ret);
}
} else {
$ret = trim($this->autocomplete($output, $question, $inputStream, \is_array($autocomplete) ? $autocomplete : iterator_to_array($autocomplete, false)));
$ret = trim($this->autocomplete($output, $question, $inputStream, $autocomplete));
}

if ($output instanceof ConsoleSectionOutput) {
Expand Down Expand Up @@ -194,17 +194,15 @@ protected function writeError(OutputInterface $output, \Exception $error)
/**
* Autocompletes a question.
*
* @param OutputInterface $output
* @param Question $question
* @param resource $inputStream
* @param resource $inputStream
*/
private function autocomplete(OutputInterface $output, Question $question, $inputStream, array $autocomplete): string
private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
{
$ret = '';

$i = 0;
$ofs = -1;
$matches = $autocomplete;
$matches = $autocomplete($ret);
$numMatches = \count($matches);

$sttyMode = shell_exec('stty -g');
Expand Down Expand Up @@ -232,7 +230,7 @@ private function autocomplete(OutputInterface $output, Question $question, $inpu

if (0 === $i) {
$ofs = -1;
$matches = $autocomplete;
$matches = $autocomplete($ret);
$numMatches = \count($matches);
} else {
$numMatches = 0;
Expand Down Expand Up @@ -260,18 +258,25 @@ private function autocomplete(OutputInterface $output, Question $question, $inpu
} elseif (\ord($c) < 32) {
if ("\t" === $c || "\n" === $c) {
if ($numMatches > 0 && -1 !== $ofs) {
$ret = $matches[$ofs];
$ret = (string) $matches[$ofs];
// Echo out remaining chars for current match
$output->write(substr($ret, $i));
$i = \strlen($ret);

$matches = array_filter(
$autocomplete($ret),
function ($match) use ($ret) {
return '' === $ret || 0 === strpos($match, $ret);
}
);
$numMatches = \count($matches);
$ofs = -1;
}

if ("\n" === $c) {
$output->write($c);
break;
}

$numMatches = 0;
}

continue;
Expand All @@ -287,7 +292,7 @@ private function autocomplete(OutputInterface $output, Question $question, $inpu
$numMatches = 0;
$ofs = 0;

foreach ($autocomplete as $value) {
foreach ($autocomplete($ret) as $value) {
// If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
if (0 === strpos($value, $ret)) {
$matches[$numMatches++] = $value;
Expand Down
45 changes: 38 additions & 7 deletions src/Symfony/Component/Console/Question/Question.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class Question
private $attempts;
private $hidden = false;
private $hiddenFallback = true;
private $autocompleterValues;
private $autocompleterCallback;
private $validator;
private $default;
private $normalizer;
Expand Down Expand Up @@ -81,7 +81,7 @@ public function isHidden()
*/
public function setHidden($hidden)
{
if ($this->autocompleterValues) {
if ($this->autocompleterCallback) {
throw new LogicException('A hidden question cannot use the autocompleter.');
}

Expand Down Expand Up @@ -121,7 +121,9 @@ public function setHiddenFallback($fallback)
*/
public function getAutocompleterValues()
{
return $this->autocompleterValues;
$callback = $this->getAutocompleterCallback();

return $callback ? $callback('') : null;
}

/**
Expand All @@ -138,17 +140,46 @@ public function setAutocompleterValues($values)
{
if (\is_array($values)) {
$values = $this->isAssoc($values) ? array_merge(array_keys($values), array_values($values)) : array_values($values);
}

if (null !== $values && !\is_array($values) && !$values instanceof \Traversable) {
$callback = static function () use ($values) {
return $values;
};
} elseif ($values instanceof \Traversable) {
$valueCache = null;
$callback = static function () use ($values, &$valueCache) {
return $valueCache ?? $valueCache = iterator_to_array($values, false);
};
} elseif (null === $values) {
$callback = null;
} else {
throw new InvalidArgumentException('Autocompleter values can be either an array, "null" or a "Traversable" object.');
}

if ($this->hidden) {
return $this->setAutocompleterCallback($callback);
}

/**
* Gets the callback function used for the autocompleter.
*/
public function getAutocompleterCallback(): ?callable
{
return $this->autocompleterCallback;
}

/**
* Sets the callback function used for the autocompleter.
*
* The callback is passed the user input as argument and should return an iterable of corresponding suggestions.
*
* @return $this
*/
public function setAutocompleterCallback(callable $callback = null): self
{
if ($this->hidden && null !== $callback) {
throw new LogicException('A hidden question cannot use the autocompleter.');
}

$this->autocompleterValues = $values;
$this->autocompleterCallback = $callback;

return $this;
}
Expand Down
61 changes: 61 additions & 0 deletions src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,67 @@ public function testAskWithAutocomplete()
$this->assertEquals('FooBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
}

public function testAskWithAutocompleteCallback()
{
if (!$this->hasSttyAvailable()) {
$this->markTestSkipped('`stty` is required to test autocomplete functionality');
}

// Po<TAB>Cr<TAB>P<DOWN ARROW><DOWN ARROW><NEWLINE>
$inputStream = $this->getInputStream("Pa\177\177o\tCr\t\033[A\033[A\033[A\n");

$dialog = new QuestionHelper();
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);

$question = new Question('What\'s for dinner?');

// A simple test callback - return an array containing the words the
// user has already completed, suffixed with all known words.
//
// Eg: If the user inputs "Potato C", the return will be:
//
// ["Potato Carrot ", "Potato Creme ", "Potato Curry ", ...]
//
// No effort is made to avoid irrelevant suggestions, as this is handled
// by the autocomplete function.
$callback = function ($input) {
$knownWords = [
'Carrot',
'Creme',
'Curry',
'Parsnip',
'Pie',
'Potato',
'Tart',
];

$inputWords = explode(' ', $input);
$lastInputWord = array_pop($inputWords);
$suggestionBase = $inputWords
? implode(' ', $inputWords).' '
: '';

return array_map(
function ($word) use ($suggestionBase) {
return $suggestionBase.$word.' ';
},
$knownWords
);
};

$question->setAutocompleterCallback($callback);

$this->assertSame(
'Potato Creme Pie',
$dialog->ask(
$this->createStreamableInputInterfaceMock($inputStream),
$this->createOutputInterface(),
$question
)
);
}

public function testAskWithAutocompleteWithNonSequentialKeys()
{
if (!$this->hasSttyAvailable()) {
Expand Down
Loading
0