优化代码生成

This commit is contained in:
JaguarJack 2020-04-29 09:02:20 +08:00
parent 7f72784bfb
commit 64c03bdfd3
5 changed files with 48 additions and 31 deletions

View File

@ -48,7 +48,7 @@ class Generator
{
$class = ucfirst($type);
(new $class)->done($params);
return (new $class)->getContent($params);
}

View File

@ -2,6 +2,7 @@
namespace catcher\generate\factory;
use catcher\CatchAdmin;
use think\facade\Db;
abstract class Factory
{
@ -81,4 +82,17 @@ abstract class Factory
return [$className, $namespace];
}
/**
*
* @time 2020年04月28日
* @param $table
* @return bool
*/
protected function hasTableExists($table)
{
$tables = Db::getConnection()->getTables();
return in_array($table, $tables);
}
}

View File

@ -8,6 +8,26 @@ use think\facade\Db;
class Model extends Factory
{
public function done($params)
{
$file = $this->getGeneratePath($params['model']);
file_put_contents($file, $this->getContent($params));
if (!file_exists($file)) {
throw new FailedException('create model failed');
}
return true;
}
/**
* get contents
*
* @time 2020年04月29日
* @param $params
* @return string|string[]
*/
public function getContent($params)
{
// TODO: Implement done() method.
$template = new Template();
@ -23,27 +43,17 @@ class Model extends Factory
}
$content = $template->useTrait($extra['soft_delete']) .
$template->name($table) .
$template->field($this->parseField($table));
$template->name($table) .
$template->field($this->parseField($table));
$class = $template->header() .
$template->nameSpace($namespace) .
$template->uses($extra['soft_delete']) .
$template->createModel($modelName, $table);
$template->nameSpace($namespace) .
$template->uses($extra['soft_delete']) .
$template->createModel($modelName, $table);
$file = $this->getGeneratePath($params['model']);
file_put_contents($file, str_replace('{CONTENT}', $content, $class));
if (!file_exists($file)) {
throw new FailedException('create model failed');
}
return true;
return str_replace('{CONTENT}', $content, $class);
}
/**
* parse field
*
@ -53,6 +63,10 @@ class Model extends Factory
*/
protected function parseField($table)
{
if (!$this->hasTableExists($table)) {
return false;
}
$columns = Db::query('show full columns from ' .
config('database.connections.mysql.prefix') . $table);

View File

@ -175,17 +175,4 @@ class SQL
$this->index .= "spatial index spatial_$field($field),". PHP_EOL;
}
}
/**
*
* @time 2020年04月28日
* @param $table
* @return bool
*/
protected function hasTableExists($table)
{
$tables = Db::getConnection()->getTables();
return in_array($table, $tables);
}
}

View File

@ -72,13 +72,15 @@ TMP;
*/
public function field($field)
{
return <<<TMP
if ($field) {
return <<<TMP
protected \$field = [
{$field}
];
TMP;
}
}