catchAdmin/extend/catcher/command/ModelGeneratorCommand.php

105 lines
2.5 KiB
PHP
Raw Normal View History

2019-12-06 09:17:40 +08:00
<?php
namespace catcher\command;
use catcher\CatchAdmin;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option as InputOption;
use think\console\Output;
use think\facade\Db;
use think\helper\Str;
class ModelGeneratorCommand extends Command
{
protected function configure()
{
$this->setName('create:model')
->addArgument('module', Argument::REQUIRED, 'module name')
2020-01-23 16:55:51 +08:00
->addArgument('model', Argument::REQUIRED, 'model name')
2019-12-06 09:17:40 +08:00
->setDescription('create model');
}
protected function execute(Input $input, Output $output)
{
$model = ucfirst($input->getArgument('model'));
$module = strtolower($input->getArgument('module'));
$table = Str::snake($model);
$modelFile= CatchAdmin::getModuleModelDirectory($module) . $model . '.php';
2020-04-17 17:10:39 +08:00
$asn = 'Y';
if (file_exists($modelFile)) {
$asn = $this->output->ask($this->input, "Model File {$model} already exists.Are you sure to overwrite, the content will be lost(Y/N)");
}
if (strtolower($asn) == 'n') {
exit(0);
}
2019-12-06 09:17:40 +08:00
file_put_contents($modelFile, $this->replaceContent([
$module, $model, $table, $this->generateFields($this->getTableFields($table))
]));
if (file_exists($modelFile)) {
$output->info(sprintf('%s Create Successfully!', $modelFile));
} else {
$output->error(sprintf('%s Create Failed!', $modelFile));
}
}
private function getTableFields($table): array
{
$fields = Db::query('show full columns from ' .
config('database.connections.mysql.prefix') . $table);
$new = [];
foreach ($fields as $field) {
$new[$field['Field']] = $field['Comment'];
}
return $new;
}
private function generateFields($fields)
{
$f = '';
foreach ($fields as $field => $comment) {
2020-04-17 17:10:39 +08:00
$f .= sprintf("'%s', // %s" . "\r\n\t\t", $field, $comment);
2019-12-06 09:17:40 +08:00
}
2020-04-17 17:10:39 +08:00
return rtrim($f, "\r\n\t\t");
2019-12-06 09:17:40 +08:00
}
private function replaceContent(array $replace)
{
return str_replace([
'{Module}', '{Class}', '{Name}', '{Field}'
], $replace, $this->content());
}
private function content()
{
return <<<EOT
<?php
2020-01-09 08:22:38 +08:00
namespace catchAdmin\{Module}\model;
2019-12-06 09:17:40 +08:00
2020-01-09 08:22:38 +08:00
use catcher\base\CatchModel;
2019-12-06 09:17:40 +08:00
2020-01-09 08:22:38 +08:00
class {Class} extends CatchModel
2019-12-06 09:17:40 +08:00
{
protected \$name = '{Name}';
protected \$field = [
2020-04-14 19:17:13 +08:00
{Field}
];
2019-12-06 09:17:40 +08:00
}
EOT;
}
}