1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100:
<?php
namespace Net\Bazzline\Component\Cli\Readline;
class Autocomplete
{
private $configuration;
public function __invoke($input, $index)
{
return $this->complete($input, $index);
}
public function complete($input, $index)
{
$configuration = $this->configuration;
if ($index == 0) {
$completion = array_keys($configuration);
} else {
$buffer = preg_replace('/\s+/', ' ', trim(readline_info('line_buffer')));
$tokens = explode(' ', $buffer);
$completion = $this->fetchCompletion($configuration, $tokens);
}
return $completion;
}
public function setConfiguration(array $configuration)
{
$this->configuration = $configuration;
return $this;
}
private function fetchCompletion(array $configuration, array &$tokens)
{
$completion = false;
$index = current($tokens);
if (isset($configuration[$index])) {
if (next($tokens) !== false) {
$completion = $this->fetchCompletion($configuration[$index], $tokens);
} else {
$arrayOrExecutable = $configuration[$index];
if (is_array($arrayOrExecutable)) {
$completion = array_keys($arrayOrExecutable);
} else {
$completion = false;
}
}
} else {
$indexLengthIsGreaterZero = (strlen($index) > 0);
if ($indexLengthIsGreaterZero) {
$position = strlen($index);
$values = array_keys($configuration);
$completion = [];
foreach ($values as $value) {
if (substr($value, 0, $position) === $index) {
$completion[] = $value;
}
}
if (empty($completion)) {
$completion = false;
}
}
}
return $completion;
}
}