Hi,
the following commands controller allows you to auto complete your custom Yii 2 commands.
I’m using this controller on my linux machine.
How can you use it in concrete? You hit
then you can type the beginning of your controller commands like
for your exporter/some-what
and after you hit the tab-button, you’ll see the auto-completion. Like you know it from the general bash terminal.
It’s expected that your commands-controllers are in the commands-folder, like the controller itself. You can find the controller below. I hope you can use it well. If you have any notes to it - please let me know.
<?php
namespace app\commands;
use yii\console\Controller;
use Yii;
/**
* Class AutoController
*
* This Controller provides command auto-completion in your command line.
*
* @package app\commands
*/
class AutoController extends Controller
{
/**
* This method reads the "commands"-folder and extracts all the commands
* from their containing controllers.
*
* @return array
*/
private static function getCommandsArray(){
$my_dir = scandir('./commands');
$commands = array();
foreach ($my_dir as $file) {
if ($file !== '.' && $file !== '..' && is_numeric(strpos($file, 'Controller.php'))) {
$class_name = str_replace('.php', '', $file);
$class_name_with_namespace = "\\app\\commands\\" . $class_name;
$class_methods = get_class_methods(new $class_name_with_namespace('controller', Yii::$app));
$commands_controller = strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $class_name));
foreach ($class_methods as $class_method) {
if (is_numeric(strpos($class_method, 'action'))) {
$method = strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $class_method));
$method = str_replace('action-', '', $method);
$commands_controller = str_replace('-controller', '', $commands_controller);
$commands[] = $commands_controller . '/' . $method;
}
}
}
}
return $commands;
}
/**
* The callback which is returning an array with strings, which will be
* auto-completed.
*
* @param $input
* @param $index
* @return array
*/
private static function completionCallback($input, $index){
return self::getCommandsArray();
}
/**
* The method which is handling the autocompletion. After it's runned, you can
* autocomplete your commands by hitting the tab-button.
*/
public function actionCompl(){
readline_completion_function(array('self', 'completionCallback'));
$command_input = readline("Custom Yii 2 command: ");
passthru('php ./yii ' . $command_input);
}
}
?>
Have fun!