Dynamic commands loader

This commit is contained in:
2020-12-23 11:35:40 +03:00
parent 404516e722
commit 733c6cda5c

View File

@@ -8,23 +8,65 @@ use Laravel\Lumen\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
HelloWorld::class
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
private function extractClass($file)
{
$fp = fopen($file, 'r');
$class = $namespace = $buffer = '';
$i = 0;
while (!$class) {
if (feof($fp)) break;
$buffer .= fread($fp, 512);
$tokens = token_get_all($buffer);
if (strpos($buffer, '{') === false) continue;
for (;$i<count($tokens);$i++) {
if ($tokens[$i][0] === T_NAMESPACE) {
for ($j=$i+1;$j<count($tokens); $j++) {
if ($tokens[$j][0] === T_STRING) {
$namespace .= '\\'.$tokens[$j][1];
} else if ($tokens[$j] === '{' || $tokens[$j] === ';') {
break;
}
}
}
if ($tokens[$i][0] === T_CLASS) {
for ($j=$i+1;$j<count($tokens);$j++) {
if ($tokens[$j] === '{') {
$class = $tokens[$i+2][1];
}
}
}
}
}
return $namespace . '\\' . $class;
}
public function getCommands()
{
$commands_path = base_path() . '/../commands';
$files = array_diff(scandir(base_path() . '/../commands'), array('.', '..'));
$classes = [];
foreach($files as $file) {
$classes[] = $this->extractClass($commands_path . '/' . $file);
}
$commands = parent::getCommands();
return array_merge($commands, $classes);
}
}