Commit fdb55ef9 authored by 王源's avatar 王源 🎧

优化mm生成命令代码

parent 800a0248
...@@ -24,10 +24,10 @@ class MakeModelCommand extends HyperfCommand ...@@ -24,10 +24,10 @@ class MakeModelCommand extends HyperfCommand
*/ */
protected $container; protected $container;
private $path = ''; private $path;
private $appPath = ''; private $appPath;
private $builder = null; private $builder;
private $table = ""; private $table = "";
private $tableIndex = 0; private $tableIndex = 0;
...@@ -38,40 +38,6 @@ class MakeModelCommand extends HyperfCommand ...@@ -38,40 +38,6 @@ class MakeModelCommand extends HyperfCommand
private $currentTableStructure = []; private $currentTableStructure = [];
private $cc = [
'bigint' => 'integer',
'int' => 'integer',
'tinyint' => 'integer',
'smallint' => 'integer',
'mediumint' => 'integer',
'integer' => 'integer',
'numeric' => 'integer',
'float' => 'float',
'real' => 'real',
'double' => 'double',
'decimal' => 'decimal',
'bool' => 'bool',
'boolean' => 'boolean',
'char' => 'string',
'tinytext' => 'string',
'text' => 'string',
'mediumtext' => 'string',
'longtext' => 'string',
'year' => 'string',
'varchar' => 'string',
'string' => 'string',
'object' => 'object',
'enum' => 'object',
'set' => 'object',
'date' => 'date',
'datetime' => 'datetime',
'custom_datetime' => 'custom_datetime',
'timestamp' => 'timestamp',
'collection' => 'collection',
'array' => 'array',
'json' => 'json',
];
public function __construct(ContainerInterface $container) public function __construct(ContainerInterface $container)
{ {
$this->container = $container; $this->container = $container;
...@@ -193,13 +159,12 @@ class MakeModelCommand extends HyperfCommand ...@@ -193,13 +159,12 @@ class MakeModelCommand extends HyperfCommand
$relation['constraint_table'] = $ts[1]; $relation['constraint_table'] = $ts[1];
$relation['constraint_table_key'] = Str::singular($ts[1]) . "_id"; $relation['constraint_table_key'] = Str::singular($ts[1]) . "_id";
$relation['local_table'] = $ts[0]; $relation['local_table'] = $ts[0];
$relation['local_table_key'] = $fv['column_name'];
} else { } else {
$relation['constraint_table'] = $ts[0]; $relation['constraint_table'] = $ts[0];
$relation['constraint_table_key'] = Str::singular($ts[0]) . "_id"; $relation['constraint_table_key'] = Str::singular($ts[0]) . "_id";
$relation['local_table'] = $ts[1]; $relation['local_table'] = $ts[1];
$relation['local_table_key'] = $fv['column_name'];
} }
$relation['local_table_key'] = $fv['column_name'];
$relation['relation_table'] = $fv['table_name']; $relation['relation_table'] = $fv['table_name'];
$relation['function'] = Str::snake($relation['constraint_table']); $relation['function'] = Str::snake($relation['constraint_table']);
$relation['relation_model_name'] = Str::studly(Str::singular($relation['constraint_table'])); $relation['relation_model_name'] = Str::studly(Str::singular($relation['constraint_table']));
...@@ -244,8 +209,8 @@ class MakeModelCommand extends HyperfCommand ...@@ -244,8 +209,8 @@ class MakeModelCommand extends HyperfCommand
$indexes = array_map('get_object_vars', $indexes); $indexes = array_map('get_object_vars', $indexes);
$indexes = collect($indexes)->groupBy("table_name")->toArray(); $indexes = collect($indexes)->groupBy("table_name")->toArray();
foreach ($tables as $k => $v) { foreach ($tables as $k => $v) {
$v['fields'] = isset($fields[$k]) ? $fields[$k] : []; $v['fields'] = $fields[$k] ?? [];
$v['constraints'] = isset($constraints[$k]) ? $constraints[$k] : []; $v['constraints'] = $constraints[$k] ?? [];
if (isset($indexes[$k])) { if (isset($indexes[$k])) {
$v['indexes'] = collect($indexes[$k])->groupBy("index_name")->toArray(); $v['indexes'] = collect($indexes[$k])->groupBy("index_name")->toArray();
} else { } else {
...@@ -260,7 +225,6 @@ class MakeModelCommand extends HyperfCommand ...@@ -260,7 +225,6 @@ class MakeModelCommand extends HyperfCommand
private function resortTable($tables) private function resortTable($tables)
{ {
$done = false; $done = false;
$tables = $tables;
while (!$done) { while (!$done) {
foreach ($tables as $k => $v) { foreach ($tables as $k => $v) {
if (!$v['constraints']) { if (!$v['constraints']) {
...@@ -311,7 +275,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -311,7 +275,7 @@ class MakeModelCommand extends HyperfCommand
$timestamps = 0; $timestamps = 0;
$softDelete = false; $softDelete = false;
$list = $info['fields']; $list = $info['fields'];
foreach ($list as $k => $v) { foreach ($list as $v) {
$name = $v['column_name']; $name = $v['column_name'];
$pc = [ $pc = [
'bigint' => 'integer', 'bigint' => 'integer',
...@@ -337,15 +301,15 @@ class MakeModelCommand extends HyperfCommand ...@@ -337,15 +301,15 @@ class MakeModelCommand extends HyperfCommand
'string' => 'string', 'string' => 'string',
'enum' => 'array', 'enum' => 'array',
'set' => 'array', 'set' => 'array',
'date' => '\Carbon\Carbon', 'date' => 'string',
'datetime' => '\Carbon\Carbon', 'datetime' => 'string',
'custom_datetime' => '\Carbon\Carbon', 'custom_datetime' => 'string',
'timestamp' => '\Carbon\Carbon', 'timestamp' => 'string',
'collection' => 'collection', 'collection' => 'collection',
'array' => 'array', 'array' => 'array',
'json' => 'string', 'json' => 'string',
]; ];
$properties .= " * @property " . (isset($pc[$v['data_type']]) ? $pc[$v['data_type']] : "string") . " $" . $name . ($v['column_comment'] ? " " . $v['column_comment'] : "") . "\n"; $properties .= " * @property " . ($pc[$v['data_type']] ?? "string") . " $" . $name . ($v['column_comment'] ? " " . $v['column_comment'] : "") . "\n";
if ($name == 'created_at' || $name == 'updated_at') { if ($name == 'created_at' || $name == 'updated_at') {
$timestamps++; $timestamps++;
} }
...@@ -431,7 +395,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -431,7 +395,7 @@ class MakeModelCommand extends HyperfCommand
{ {
$author = $this->input->getOption("author"); $author = $this->input->getOption("author");
$patterns = array_merge($patterns, ['%user%', '%date%', '%time%']); $patterns = array_merge($patterns, ['%user%', '%date%', '%time%']);
$replacements = array_merge($replacements, [$author ? $author : "Auto generated.", date("Y-m-d"), date("h:i:s")]); $replacements = array_merge($replacements, [$author ?: "Auto generated.", date("Y-m-d"), date("h:i:s")]);
return str_replace($patterns, $replacements, $content); return str_replace($patterns, $replacements, $content);
} }
...@@ -449,8 +413,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -449,8 +413,7 @@ class MakeModelCommand extends HyperfCommand
} }
file_put_contents($file, $content); file_put_contents($file, $content);
$file = pathinfo($file, PATHINFO_FILENAME); $file = pathinfo($file, PATHINFO_FILENAME);
$this->info("<info>[INFO] Created File:</info> $file");
$this->info("<info>[INFO] Created File:</info> {$file}");
return true; return true;
} }
...@@ -500,9 +463,9 @@ class MakeModelCommand extends HyperfCommand ...@@ -500,9 +463,9 @@ class MakeModelCommand extends HyperfCommand
//显示 //显示
$show = "\$info = \$this->model\n"; $show = "\$info = \$this->model\n";
//新增 //新增
$create = "/** @var {$modelClass} \$model */\n \t\t\t\$model = parent::create(\$attributes);\n"; $create = "/** @var $modelClass \$model */\n \t\t\t\$model = parent::create(\$attributes);\n";
//新增 //新增
$update = "/** @var {$modelClass} \$model */\n \t\t\t\$model = parent::update(\$attributes, \$id);\n"; $update = "/** @var $modelClass \$model */\n \t\t\t\$model = parent::update(\$attributes, \$id);\n";
//删除 //删除
$delete = ''; $delete = '';
//关联查询 //关联查询
...@@ -513,7 +476,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -513,7 +476,7 @@ class MakeModelCommand extends HyperfCommand
$list .= "\n\t\t->with(["; $list .= "\n\t\t->with([";
$show .= "\n\t\t->with(["; $show .= "\n\t\t->with([";
$t = []; $t = [];
foreach ($info['relations']['belongsTo'] as $k => $v) { foreach ($info['relations']['belongsTo'] as $v) {
$x = "\n\t\t\t'" . $v['function'] . "' => function (\$q) {\n"; $x = "\n\t\t\t'" . $v['function'] . "' => function (\$q) {\n";
$fields = $this->listColumns($v['relation_table']); $fields = $this->listColumns($v['relation_table']);
$fields = collect($fields['fields'])->keyBy('column_name') $fields = collect($fields['fields'])->keyBy('column_name')
...@@ -551,7 +514,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -551,7 +514,7 @@ class MakeModelCommand extends HyperfCommand
if (isset($info['relations']['hasMany'])) { if (isset($info['relations']['hasMany'])) {
foreach ($info['relations']['hasMany'] as $v) { foreach ($info['relations']['hasMany'] as $v) {
$f = Str::camel($v['function']); $f = Str::camel($v['function']);
$rs .= "\n\tpublic function {$f}(\$id): array\n"; $rs .= "\n\tpublic function $f(\$id): array\n";
$rs .= "\t{\n"; $rs .= "\t{\n";
$rs .= "\t\t\$pageSize = (int)\$this->request->input('page_size', DEFAULT_PAGE_SIZE);\n"; $rs .= "\t\t\$pageSize = (int)\$this->request->input('page_size', DEFAULT_PAGE_SIZE);\n";
$rs .= "\t\treturn \$this->find(\$id)->{$v['function']}()->orderByDesc('id')->paginate(\$pageSize)->toArray();\n"; $rs .= "\t\treturn \$this->find(\$id)->{$v['function']}()->orderByDesc('id')->paginate(\$pageSize)->toArray();\n";
...@@ -577,14 +540,12 @@ class MakeModelCommand extends HyperfCommand ...@@ -577,14 +540,12 @@ class MakeModelCommand extends HyperfCommand
private function listColumns($table) private function listColumns($table)
{ {
$table = trim($table); $table = trim($table);
$table = isset($this->allTableStructures[$table]) ? $this->allTableStructures[$table] : []; return $this->allTableStructures[$table] ?? [];
return $table;
} }
/** /**
* 添加类到依赖注入配置文件 * 添加类到依赖注入配置文件
* @param $modelClass * @param $modelClass
* @return bool
*/ */
private function addDepends($modelClass) private function addDepends($modelClass)
{ {
...@@ -592,12 +553,11 @@ class MakeModelCommand extends HyperfCommand ...@@ -592,12 +553,11 @@ class MakeModelCommand extends HyperfCommand
if (file_exists($file)) { if (file_exists($file)) {
$content = file_get_contents($file); $content = file_get_contents($file);
if (strpos($content, "\App\Repository\Interfaces\\" . $modelClass . "Repository::class") !== false) { if (strpos($content, "\App\Repository\Interfaces\\" . $modelClass . "Repository::class") !== false) {
return true; return;
} }
$content = str_replace("]", " \\App\\Repository\\Interfaces\\" . $modelClass . "Repository::class => \\App\\Repository\\Eloquent\\" . $modelClass . "RepositoryEloquent::class,\n]", $content); $content = str_replace("]", " \\App\\Repository\\Interfaces\\" . $modelClass . "Repository::class => \\App\\Repository\\Eloquent\\" . $modelClass . "RepositoryEloquent::class,\n]", $content);
$this->writeToFile($file, $content); $this->writeToFile($file, $content);
} }
} }
private function makeController() private function makeController()
...@@ -627,9 +587,9 @@ class MakeModelCommand extends HyperfCommand ...@@ -627,9 +587,9 @@ class MakeModelCommand extends HyperfCommand
$rs .= "\n\t * @param; \$id id编号"; $rs .= "\n\t * @param; \$id id编号";
$rs .= "\n\t * @return mixed"; $rs .= "\n\t * @return mixed";
$rs .= "\n\t */"; $rs .= "\n\t */";
$rs .= "\n\tpublic function {$f}(\$id)\n"; $rs .= "\n\tpublic function $f(\$id)\n";
$rs .= "\t{\n"; $rs .= "\t{\n";
$rs .= "\t\t\$data = \$this->repository->{$f}(\$id);\n"; $rs .= "\t\t\$data = \$this->repository->$f(\$id);\n";
$rs .= "\t\treturn success('获取成功', \$data);\n"; $rs .= "\t\treturn success('获取成功', \$data);\n";
$rs .= "\t}\n"; $rs .= "\t}\n";
$routes[] = $v['function']; $routes[] = $v['function'];
...@@ -645,9 +605,10 @@ class MakeModelCommand extends HyperfCommand ...@@ -645,9 +605,10 @@ class MakeModelCommand extends HyperfCommand
$this->addRoutes($modelClass, $routes); $this->addRoutes($modelClass, $routes);
} }
/**添加Controller到路由类 /**
* 添加Controller到路由类
* @param $modelClass * @param $modelClass
* @return bool * @param array $routes
*/ */
private function addRoutes($modelClass, $routes = []) private function addRoutes($modelClass, $routes = [])
{ {
...@@ -657,20 +618,20 @@ class MakeModelCommand extends HyperfCommand ...@@ -657,20 +618,20 @@ class MakeModelCommand extends HyperfCommand
$content = file_get_contents($file); $content = file_get_contents($file);
$group = str_replace("_", "/", Str::snake($table)); $group = str_replace("_", "/", Str::snake($table));
if (strpos($content, "Router::addGroup('" . $group . "', function () {") !== false) { if (strpos($content, "Router::addGroup('" . $group . "', function () {") !== false) {
return true; return;
} }
$info = $this->currentTableStructure; $info = $this->currentTableStructure;
$tableComment = (isset($info['table_comment']) && $info['table_comment']) ? $info['table_comment'] : $table; $tableComment = (isset($info['table_comment']) && $info['table_comment']) ? $info['table_comment'] : $table;
$content .= "\n\t// " . $tableComment; $content .= "\n\t// " . $tableComment;
$content .= "\n\tRouter::addGroup('" . $group . "', function () {"; $content .= "\n\tRouter::addGroup('" . $group . "', function () {";
$content .= "\n\t\tRouter::get('', 'App\Controller\\" . $modelClass . "Controller@index');"; $content .= "\n\t\tRouter::get('', 'App\Controller\\" . $modelClass . "Controller@index');";
$content .= "\n\t\tRouter::get('/{id}', 'App\Controller\\" . $modelClass . "Controller@show');"; $content .= "\n\t\tRouter::get('/{id:\d+}', 'App\Controller\\" . $modelClass . "Controller@show');";
$content .= "\n\t\tRouter::post('', 'App\Controller\\" . $modelClass . "Controller@create');"; $content .= "\n\t\tRouter::post('', 'App\Controller\\" . $modelClass . "Controller@create');";
$content .= "\n\t\tRouter::patch('/{id}', 'App\Controller\\" . $modelClass . "Controller@update');"; $content .= "\n\t\tRouter::patch('/{id:\d+}', 'App\Controller\\" . $modelClass . "Controller@update');";
$content .= "\n\t\tRouter::delete('/{id}', 'App\Controller\\" . $modelClass . "Controller@delete');"; $content .= "\n\t\tRouter::delete('/{id:\d+}', 'App\Controller\\" . $modelClass . "Controller@delete');";
if ($routes) { if ($routes) {
foreach ($routes as $v) { foreach ($routes as $v) {
$content .= "\n\t\tRouter::get('/$v/\{id\}', 'App\Controller\\" . $modelClass . "Controller@$v');"; $content .= "\n\t\tRouter::get('/$v/{id:\d+}', 'App\Controller\\" . $modelClass . "Controller@$v');";
} }
} }
$content .= "\n\t});"; $content .= "\n\t});";
...@@ -695,7 +656,6 @@ class MakeModelCommand extends HyperfCommand ...@@ -695,7 +656,6 @@ class MakeModelCommand extends HyperfCommand
$filterFields = ["id", "created_at", "updated_at", "deleted_at"]; $filterFields = ["id", "created_at", "updated_at", "deleted_at"];
$rules = ''; $rules = '';
$attributes = ''; $attributes = '';
$messages = [];
$list = $info['fields']; $list = $info['fields'];
foreach ($list as $v) { foreach ($list as $v) {
$name = $v['column_name']; $name = $v['column_name'];
...@@ -703,10 +663,8 @@ class MakeModelCommand extends HyperfCommand ...@@ -703,10 +663,8 @@ class MakeModelCommand extends HyperfCommand
$type = $v['data_type']; $type = $v['data_type'];
$key = $v['column_key']; $key = $v['column_key'];
$null = $v['is_nullable']; $null = $v['is_nullable'];
// $extra = $v['extra'];
$comment = $v['column_comment']; $comment = $v['column_comment'];
$length = $v['length']; $length = $v['length'];
$msgName = ($comment ? $comment : $name);
if (in_array($name, $filterFields)) { if (in_array($name, $filterFields)) {
continue; continue;
} }
...@@ -715,7 +673,6 @@ class MakeModelCommand extends HyperfCommand ...@@ -715,7 +673,6 @@ class MakeModelCommand extends HyperfCommand
if ($null !== 'YES') { if ($null !== 'YES') {
if ($default !== '' && $default !== '0' && !$default) { if ($default !== '' && $default !== '0' && !$default) {
$required = "required"; $required = "required";
$messages[] = "\t\t'{$name}.{$required}' => '{$msgName}不能为空!'";
} }
} }
$rs[] = $required; $rs[] = $required;
...@@ -727,7 +684,6 @@ class MakeModelCommand extends HyperfCommand ...@@ -727,7 +684,6 @@ class MakeModelCommand extends HyperfCommand
case "int": case "int":
case "integer": case "integer":
$rs[] = 'integer'; $rs[] = 'integer';
$messages[] = "\t\t'{$name}.integer' => '{$msgName}只能是整数!'";
break; break;
case "decimal": case "decimal":
case "double": case "double":
...@@ -735,7 +691,6 @@ class MakeModelCommand extends HyperfCommand ...@@ -735,7 +691,6 @@ class MakeModelCommand extends HyperfCommand
case "numeric": case "numeric":
case "real": case "real":
$rs[] = 'numeric'; $rs[] = 'numeric';
$messages[] = "\t\t'{$name}.numeric' => '{$msgName}只能是数字支持小数!'";
break; break;
case "char": case "char":
case "varchar": case "varchar":
...@@ -746,7 +701,6 @@ class MakeModelCommand extends HyperfCommand ...@@ -746,7 +701,6 @@ class MakeModelCommand extends HyperfCommand
$rs[] = 'string'; $rs[] = 'string';
if ($length) { if ($length) {
$rs[] = 'max:' . $length; $rs[] = 'max:' . $length;
$messages[] = "\t\t'{$name}.max' => '{$msgName}字符长度不能超过{$length}!'";
} }
break; break;
case "date": case "date":
...@@ -755,46 +709,39 @@ class MakeModelCommand extends HyperfCommand ...@@ -755,46 +709,39 @@ class MakeModelCommand extends HyperfCommand
case "timestamp": case "timestamp":
case "year": case "year":
$rs[] = 'date'; $rs[] = 'date';
$messages[] = "\t\t'{$name}.date' => '{$msgName}不符合日期时间格式!'";
break; break;
case "enum": case "enum":
case "set": case "set":
$rs[] = 'in:[' . $length . "]"; $rs[] = 'in:[' . $length . "]";
$messages[] = "\t\t'{$name}.in' => '{$msgName}的值只能在[{$length}]列表中!'";
break; break;
default: default:
if (Str::contains($name, "email") || Str::contains($name, "e-mail") || Str::contains($name, "e_mail")) { if (Str::contains($name, "email") || Str::contains($name, "e-mail") || Str::contains($name, "e_mail")) {
$rs[] = 'email'; $rs[] = 'email';
$messages[] = "\t\t'{$name}.email' => '{$msgName}只支持邮箱格式!'";
} elseif ($name == 'url' } elseif ($name == 'url'
|| Str::contains($name, "_url") || Str::contains($name, "_url")
|| Str::contains($name, "url_")) { || Str::contains($name, "url_")) {
$rs[] = 'url'; $rs[] = 'url';
$messages[] = "\t\t'{$name}.email' => '{$msgName}只支持url格式!'";
} elseif ($name == 'date' } elseif ($name == 'date'
|| Str::contains($name, "_date") || Str::contains($name, "_date")
|| Str::contains($name, "date_")) { || Str::contains($name, "date_")) {
$rs[] = 'date'; $rs[] = 'date';
$messages[] = "\t\t'{$name}.email' => '{$msgName}不符合日期时间格式!'";
} }
break; break;
} }
if ($key == 'uni') { if ($key == 'uni') {
$rs[] = "unique:$table," . $name; $rs[] = "unique:$table," . $name;
$messages[] = "\t\t'{$name}.unique' => '{$msgName}的值在数据库中已经存在!'";
} }
if ($comment) { if ($comment) {
$attributes .= "\t\t'" . $name . "' => '" . $comment . "'," . "\n"; $attributes .= "\t\t'" . $name . "' => '" . $comment . "'," . "\n";
} }
$rules .= "\t\t\t'" . $name . "' => '" . implode("|", $rs) . "'," . ($comment ? "// " . $comment . "-" . $type : "//" . $type) . "\n"; $rules .= "\t\t\t'" . $name . "' => '" . implode("|", $rs) . "'," . ($comment ? "// " . $comment . "-" . $type : "//" . $type) . "\n";
} }
$messages = join(",\n", $messages); $patterns = ["%ModelClass%", '%createRules%', '%updateRules%', '%attributes%'];
$patterns = ["%ModelClass%", '%createRules%', '%updateRules%', '%attributes%', '%messages%'];
$createRules = $rules; $createRules = $rules;
$updateRules = str_replace("nullable", "sometimes|nullable", $rules); $updateRules = str_replace("nullable", "sometimes|nullable", $rules);
$updateRules = str_replace("required", "sometimes|required", $updateRules); $updateRules = str_replace("required", "sometimes|required", $updateRules);
$replacements = [$modelClass, $createRules, $updateRules, $attributes, $messages]; $replacements = [$modelClass, $createRules, $updateRules, $attributes];
$content = $this->buildField($patterns, $replacements, $content); $content = $this->buildField($patterns, $replacements, $content);
$this->writeToFile($file, $content); $this->writeToFile($file, $content);
} }
...@@ -814,14 +761,13 @@ class MakeModelCommand extends HyperfCommand ...@@ -814,14 +761,13 @@ class MakeModelCommand extends HyperfCommand
$fields = []; $fields = [];
$otherModel = []; $otherModel = [];
$generateCount = $this->input->getOption("seeder"); $generateCount = $this->input->getOption("seeder");
$generateCount = $generateCount ? $generateCount : 30; $generateCount = $generateCount ?: 30;
$otherProcess = ""; $otherProcess = "";
$list = $info['fields']; $list = $info['fields'];
$maxNumber = 4; $maxNumber = 4;
foreach ($list as $v) { foreach ($list as $v) {
$name = $v['column_name']; $name = $v['column_name'];
$type = $v['data_type']; $type = $v['data_type'];
$nullAble = ($v['is_nullable'] !== 'YES');
$length = explode(" ", $v['length']); $length = explode(" ", $v['length']);
if (in_array($name, $filterFields)) { if (in_array($name, $filterFields)) {
continue; continue;
...@@ -835,25 +781,25 @@ class MakeModelCommand extends HyperfCommand ...@@ -835,25 +781,25 @@ class MakeModelCommand extends HyperfCommand
case "int": case "int":
case "integer": case "integer":
if ($name == "sex") { if ($name == "sex") {
$fields[] = "\t\t\t\t'{$name}' => \$faker->randomElement([0,1]),"; $fields[] = "\t\t\t\t'$name' => \$faker->randomElement([0,1]),";
} else if (Str::contains($name, "status")) { } else if (Str::contains($name, "status")) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->randomDigit,"; $fields[] = "\t\t\t\t'$name' => \$faker->randomDigit,";
} else if (Str::endsWith($name, "_id")) { } else if (Str::endsWith($name, "_id")) {
$o = str_replace("_id", "", $name); $o = str_replace("_id", "", $name);
$os = Str::plural($o); $os = Str::plural($o);
if (in_array($os, $this->tables)) { if (in_array($os, $this->tables)) {
$o = Str::studly($o); $o = Str::studly($o);
$otherModel[] = "\nuse App\Model\\" . $o . ";"; $otherModel[] = "\nuse App\Model\\" . $o . ";";
$fields[] = "\t\t\t\t'{$name}' => $o::orderBy(Db::raw('rand()'))->first()->id,"; $fields[] = "\t\t\t\t'$name' => $o::orderBy(Db::raw('rand()'))->first()->id,";
} else { } else {
$n = ((isset($length[0]) && $length[0] && $length[0] < $maxNumber) ? $length[0] : $maxNumber); $n = ((isset($length[0]) && $length[0] && $length[0] < $maxNumber) ? $length[0] : $maxNumber);
$n = rand(1, $n); $n = rand(1, $n);
$fields[] = "\t\t\t\t'{$name}' => \$faker->randomNumber($n),"; $fields[] = "\t\t\t\t'$name' => \$faker->randomNumber($n),";
} }
} else { } else {
$n = ((isset($length[0]) && $length[0] < $maxNumber) ? $length[0] : $maxNumber); $n = ((isset($length[0]) && $length[0] < $maxNumber) ? $length[0] : $maxNumber);
$n = rand(1, $n); $n = rand(1, $n);
$fields[] = "\t\t\t\t'{$name}' => \$faker->randomNumber($n),"; $fields[] = "\t\t\t\t'$name' => \$faker->randomNumber($n),";
} }
break; break;
case "decimal": case "decimal":
...@@ -865,93 +811,91 @@ class MakeModelCommand extends HyperfCommand ...@@ -865,93 +811,91 @@ class MakeModelCommand extends HyperfCommand
$n = rand(1, $n); $n = rand(1, $n);
$n2 = ((isset($length[1]) && $length[1] < $maxNumber) ? $length[1] : 2); $n2 = ((isset($length[1]) && $length[1] < $maxNumber) ? $length[1] : 2);
$n3 = $n2 + 20; $n3 = $n2 + 20;
$fields[] = "\t\t\t\t'{$name}' => \$faker->randomFloat($n,$n2,$n3),"; $fields[] = "\t\t\t\t'$name' => \$faker->randomFloat($n,$n2,$n3),";
break; break;
case "char": case "char":
case "varchar": case "varchar":
$n = ((isset($length[0]) && $length[0]) ? $length[0] : 255); $n = ((isset($length[0]) && $length[0]) ? $length[0] : 255);
if ($name == "ip" || $name == "ip" || $name == "ip_address" || $name == "ip_addr") { if ($name == "ip" || $name == "ip_address" || $name == "ip_addr") {
$fields[] = "\t\t\t\t'{$name}' => \$faker->ipv4,"; $fields[] = "\t\t\t\t'$name' => \$faker->ipv4,";
} else if (Str::contains($name, "email")) { } else if (Str::contains($name, "email")) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->email,"; $fields[] = "\t\t\t\t'$name' => \$faker->email,";
} else if ($name == "userName" || $name == "user_name" || $name == "uname") { } else if ($name == "userName" || $name == "user_name" || $name == "uname") {
$fields[] = "\t\t\t\t'{$name}' => \$faker->userName,"; $fields[] = "\t\t\t\t'$name' => \$faker->userName,";
} else if ($name == "url" || $name == "domain" || Str::endsWith($name, "_url") || Str::startsWith($name, "url_")) { } else if ($name == "url" || $name == "domain" || Str::endsWith($name, "_url") || Str::startsWith($name, "url_")) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->url,"; $fields[] = "\t\t\t\t'$name' => \$faker->url,";
} else if ($name == "company" || $name == "company_name") { } else if ($name == "company" || $name == "company_name") {
$fields[] = "\t\t\t\t'{$name}' => \$faker->company,"; $fields[] = "\t\t\t\t'$name' => \$faker->company,";
} else if ($name == "gender") { } else if ($name == "gender") {
$fields[] = "\t\t\t\t'{$name}' => \$faker->title(),"; $fields[] = "\t\t\t\t'$name' => \$faker->title(),";
} else if ($name == "name") { } else if ($name == "name") {
$fields[] = "\t\t\t\t'{$name}' => \$faker->name(),"; $fields[] = "\t\t\t\t'$name' => \$faker->name(),";
} else if (Str::contains($name, "city")) { } else if (Str::contains($name, "city")) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->city,"; $fields[] = "\t\t\t\t'$name' => \$faker->city,";
} else if (Str::contains($name, "street") || Str::contains($name, "address")) { } else if (Str::contains($name, "street") || Str::contains($name, "address")) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->streetAddress,"; $fields[] = "\t\t\t\t'$name' => \$faker->streetAddress,";
} else if (Str::contains($name, "postcode")) { } else if (Str::contains($name, "postcode")) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->postcode,"; $fields[] = "\t\t\t\t'$name' => \$faker->postcode,";
} else if (Str::contains($name, "country")) { } else if (Str::contains($name, "country")) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->country,"; $fields[] = "\t\t\t\t'$name' => \$faker->country,";
} else if (Str::contains($name, "phoneNumber") || $name == "tel" || $name == "mobile" || Str::contains($name, "phone")) { } else if (Str::contains($name, "phoneNumber") || $name == "tel" || $name == "mobile" || Str::contains($name, "phone")) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->phoneNumber,"; $fields[] = "\t\t\t\t'$name' => \$faker->phoneNumber,";
} else if (Str::contains($name, "color")) { } else if (Str::contains($name, "color")) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->colorName,"; $fields[] = "\t\t\t\t'$name' => \$faker->colorName,";
} else if (Str::contains($name, "image") || Str::contains($name, "path")) { } else if (Str::contains($name, "image") || Str::contains($name, "path")) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->imageUrl(640, 480),"; $fields[] = "\t\t\t\t'$name' => \$faker->imageUrl(640, 480),";
} else if ($name == "ean" || $name == "bar_code") { } else if ($name == "ean" || $name == "bar_code") {
$fields[] = "\t\t\t\t'{$name}' => \$faker->ean13,"; $fields[] = "\t\t\t\t'$name' => \$faker->ean13,";
} else if ($n < 10) { } else if ($n < 10) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->word,"; $fields[] = "\t\t\t\t'$name' => \$faker->word,";
} elseif ($n < 100) { } elseif ($n < 100) {
$fields[] = "\t\t\t\t'{$name}' => \$faker->sentence(6),"; $fields[] = "\t\t\t\t'$name' => \$faker->sentence(6),";
} else { } else {
$n = rand(2, 5); $n = rand(2, 5);
$fields[] = "\t\t\t\t'{$name}' => \$faker->paragraph($n, true),"; $fields[] = "\t\t\t\t'$name' => \$faker->paragraph($n, true),";
} }
break; break;
case "tinytext": case "tinytext":
case "mediumtext": case "mediumtext":
case "longtext": case "longtext":
case "text": case "text":
$fields[] = "\t\t\t\t'{$name}' => \$faker->text,"; $fields[] = "\t\t\t\t'$name' => \$faker->text,";
break; break;
case "date": case "date":
$fields[] = "\t\t\t\t'{$name}' => \$faker->date('Y-m-d'),"; $fields[] = "\t\t\t\t'$name' => \$faker->date('Y-m-d'),";
break; break;
case "datetime": case "datetime":
$fields[] = "\t\t\t\t'{$name}' => \$faker->date('Y-m-d').' '.\$faker->time('H:i:s'),"; $fields[] = "\t\t\t\t'$name' => \$faker->date('Y-m-d').' '.\$faker->time('H:i:s'),";
break; break;
case "time": case "time":
$fields[] = "\t\t\t\t'{$name}' => \$faker->time('H:i:s'),"; $fields[] = "\t\t\t\t'$name' => \$faker->time('H:i:s'),";
break; break;
case "timestamp": case "timestamp":
if ($name == 'created_at' || $name == 'updated_at' || $name == 'deleted_at') { if ($name == 'created_at' || $name == 'updated_at' || $name == 'deleted_at') {
$fields[] = "\t\t\t\t'{$name}' => \$faker->date('Y-m-d').' '.\$faker->time('H:i:s'),"; $fields[] = "\t\t\t\t'$name' => \$faker->date('Y-m-d').' '.\$faker->time('H:i:s'),";
} else { } else {
$fields[] = "\t\t\t\t'{$name}' => \$faker->unixTime(),"; $fields[] = "\t\t\t\t'$name' => \$faker->unixTime(),";
} }
break; break;
case "year": case "year":
$fields[] = "\t\t\t\t'{$name}' => \$faker->year(),"; $fields[] = "\t\t\t\t'$name' => \$faker->year(),";
break; break;
case "enum": case "enum":
case "set": case "set":
$n = implode(",", $length); $n = implode(",", $length);
$fields[] = "\t\t\t\t'{$name}' => \$faker->randomElement([$n]),"; $fields[] = "\t\t\t\t'$name' => \$faker->randomElement([$n]),";
break; break;
default: default:
$fields[] = "\t\t\t\t'{$name}' => \$faker->word,"; $fields[] = "\t\t\t\t'$name' => \$faker->word,";
break; break;
} }
} }
$fields = join("\n", $fields); $fields = join("\n", $fields);
$otherModel = join("", $otherModel); $otherModel = join("", $otherModel);
//if(isset($info['']))
$patterns = ["%modelClass%", '%className%', '%otherModel%', '%generateCount%', '%fields%', '%otherProcess%']; $patterns = ["%modelClass%", '%className%', '%otherModel%', '%generateCount%', '%fields%', '%otherProcess%'];
$replacements = [$modelClass, $className, $otherModel, $generateCount, $fields, $otherProcess]; $replacements = [$modelClass, $className, $otherModel, $generateCount, $fields, $otherProcess];
$content = $this->buildField($patterns, $replacements, $content); $content = $this->buildField($patterns, $replacements, $content);
$this->writeToFile($file, $content); $this->writeToFile($file, $content);
$this->addSeeder(); $this->addSeeder();
} }
...@@ -966,7 +910,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -966,7 +910,7 @@ class MakeModelCommand extends HyperfCommand
} }
$content = file_get_contents($file); $content = file_get_contents($file);
if (strpos($content, Str::studly($this->table) . "TableSeeder::class") !== false) { if (strpos($content, Str::studly($this->table) . "TableSeeder::class") !== false) {
return true; return;
} }
$content = str_replace("];", "\t\t\t" . Str::studly($this->table) . "TableSeeder::class,\n\t\t];", $content); $content = str_replace("];", "\t\t\t" . Str::studly($this->table) . "TableSeeder::class,\n\t\t];", $content);
$this->writeToFile($file, $content); $this->writeToFile($file, $content);
...@@ -994,7 +938,6 @@ class MakeModelCommand extends HyperfCommand ...@@ -994,7 +938,6 @@ class MakeModelCommand extends HyperfCommand
$default = $v['column_default']; $default = $v['column_default'];
$type = $v['data_type']; $type = $v['data_type'];
$collation = $v['collation_name']; $collation = $v['collation_name'];
$key = $v['column_key'];
$null = $v['is_nullable']; $null = $v['is_nullable'];
$extra = $v['extra']; $extra = $v['extra'];
$comment = $v['column_comment']; $comment = $v['column_comment'];
...@@ -1037,7 +980,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -1037,7 +980,7 @@ class MakeModelCommand extends HyperfCommand
'numeric' => 'decimal', 'numeric' => 'decimal',
'real' => 'double', 'real' => 'double',
]; ];
$t .= (isset($tc[$type]) ? $tc[$type] : $type) . "('" . $name . "'"; $t .= ($tc[$type] ?? $type) . "('" . $name . "'";
if ($length) { if ($length) {
$length = explode(" ", $length); $length = explode(" ", $length);
$length = explode(",", $length[0]); $length = explode(",", $length[0]);
...@@ -1079,7 +1022,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -1079,7 +1022,7 @@ class MakeModelCommand extends HyperfCommand
$tc = [ $tc = [
'datetime' => 'dateTime', 'datetime' => 'dateTime',
]; ];
$t .= (isset($tc[$type]) ? $tc[$type] : $type) . "('" . $name . "')"; $t .= ($tc[$type] ?? $type) . "('" . $name . "')";
break; break;
case "binary": case "binary":
case "varbinary": case "varbinary":
...@@ -1094,7 +1037,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -1094,7 +1037,7 @@ class MakeModelCommand extends HyperfCommand
$tc = [ $tc = [
'set' => 'enum', 'set' => 'enum',
]; ];
$t .= (isset($tc[$type]) ? $tc[$type] : $type) . "('" . $name . "'"; $t .= ($tc[$type] ?? $type) . "('" . $name . "'";
$t .= ", [{ $t .= ", [{
$length}])"; $length}])";
break; break;
...@@ -1115,7 +1058,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -1115,7 +1058,7 @@ class MakeModelCommand extends HyperfCommand
'multipolygon' => 'multiPolygon', 'multipolygon' => 'multiPolygon',
'multilinestring' => 'multiLineString', 'multilinestring' => 'multiLineString',
]; ];
$t .= (isset($tc[$type]) ? $tc[$type] : $type) . "('" . $name . "'"; $t .= ($tc[$type] ?? $type) . "('" . $name . "'";
if ($length) { if ($length) {
$t .= ", " . $length; $t .= ", " . $length;
} }
...@@ -1158,20 +1101,20 @@ class MakeModelCommand extends HyperfCommand ...@@ -1158,20 +1101,20 @@ class MakeModelCommand extends HyperfCommand
$fields = implode("','", $fields); $fields = implode("','", $fields);
if ($k == 'PRIMARY') { if ($k == 'PRIMARY') {
if (!$pri) { if (!$pri) {
$attributes[] = "\t\t\t\$table->primary(['{$fields}']);"; $attributes[] = "\t\t\t\$table->primary(['$fields']);";
} }
} else { } else {
if ($v[0]['non_unique'] === 0) { if ($v[0]['non_unique'] === 0) {
$attributes[] = "\t\t\t\$table->unique(['{$fields}'], '{$k}');"; $attributes[] = "\t\t\t\$table->unique(['$fields'], '$k');";
} else { } else {
$attributes[] = "\t\t\t\$table->index(['{$fields}'], '{$k}');"; $attributes[] = "\t\t\t\$table->index(['$fields'], '$k');";
} }
} }
} }
} }
//外键 //外键
if ($info['constraints']) { if ($info['constraints']) {
foreach ($info['constraints'] as $k => $v) { foreach ($info['constraints'] as $v) {
$t = "\t\t\t\$table->foreign('{$v['column_name']}','{$v['constraint_name']}')->references('{$v['referenced_column_name']}')->on('{$v['referenced_table_name']}')"; $t = "\t\t\t\$table->foreign('{$v['column_name']}','{$v['constraint_name']}')->references('{$v['referenced_column_name']}')->on('{$v['referenced_table_name']}')";
if ($v['delete_rule']) { if ($v['delete_rule']) {
$t .= "->onDelete('{$v['delete_rule']}')"; $t .= "->onDelete('{$v['delete_rule']}')";
...@@ -1187,7 +1130,7 @@ class MakeModelCommand extends HyperfCommand ...@@ -1187,7 +1130,7 @@ class MakeModelCommand extends HyperfCommand
if (isset($info['table_comment']) && $info['table_comment']) { if (isset($info['table_comment']) && $info['table_comment']) {
$tableComment = 'Db::statement("alter table `' . $table . '` comment \'' . $info['table_comment'] . '\'");'; $tableComment = 'Db::statement("alter table `' . $table . '` comment \'' . $info['table_comment'] . '\'");';
} }
$patterns = ["%ClassName%", '%tablename%', '%attributes%', '%tableComment%']; $patterns = ["%ClassName%", '%tableName%', '%attributes%', '%tableComment%'];
$replacements = [$className, $table, $attributes, $tableComment]; $replacements = [$className, $table, $attributes, $tableComment];
$content = $this->buildField($patterns, $replacements, $content); $content = $this->buildField($patterns, $replacements, $content);
$this->writeToFile($file, $content); $this->writeToFile($file, $content);
...@@ -1204,7 +1147,6 @@ class MakeModelCommand extends HyperfCommand ...@@ -1204,7 +1147,6 @@ class MakeModelCommand extends HyperfCommand
public function configure() public function configure()
{ {
//$this->call()
parent::configure(); parent::configure();
$this->addOption('all', 'a', InputOption::VALUE_NONE, '生成所有文件'); $this->addOption('all', 'a', InputOption::VALUE_NONE, '生成所有文件');
$this->addOption('model', 'm', InputOption::VALUE_NONE, '生成model文件'); $this->addOption('model', 'm', InputOption::VALUE_NONE, '生成model文件');
......
...@@ -21,6 +21,7 @@ use Meibuyu\Micro\Annotation\Perm; ...@@ -21,6 +21,7 @@ use Meibuyu\Micro\Annotation\Perm;
*/ */
class %ModelClass%Controller extends AbstractController class %ModelClass%Controller extends AbstractController
{ {
/** /**
* @Inject() * @Inject()
* @var %ModelClass%Repository * @var %ModelClass%Repository
......
...@@ -7,20 +7,21 @@ ...@@ -7,20 +7,21 @@
* Description: * Description:
*/ */
use Hyperf\Database\Schema\Schema;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Migrations\Migration; use Hyperf\Database\Migrations\Migration;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Schema\Schema;
use Hyperf\DbConnection\Db; use Hyperf\DbConnection\Db;
class %ClassName% extends Migration class %ClassName% extends Migration
{ {
/** /**
* Run the migrations. * Run the migrations.
*/ */
public function up(): void public function up(): void
{ {
Schema::disableForeignKeyConstraints(); Schema::disableForeignKeyConstraints();
Schema::create('%tablename%', function (Blueprint $table) { Schema::create('%tableName%', function (Blueprint $table) {
%attributes% %attributes%
}); });
%tableComment% %tableComment%
...@@ -33,7 +34,8 @@ class %ClassName% extends Migration ...@@ -33,7 +34,8 @@ class %ClassName% extends Migration
public function down(): void public function down(): void
{ {
Schema::disableForeignKeyConstraints(); Schema::disableForeignKeyConstraints();
Schema::dropIfExists('%tablename%'); Schema::dropIfExists('%tableName%');
Schema::enableForeignKeyConstraints(); Schema::enableForeignKeyConstraints();
} }
} }
...@@ -25,19 +25,11 @@ use Meibuyu\Micro\Repository\Eloquent\BaseRepository; ...@@ -25,19 +25,11 @@ use Meibuyu\Micro\Repository\Eloquent\BaseRepository;
class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelClass%Repository class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelClass%Repository
{ {
/**
* %ModelClass% 模型
* @return mixed
*/
public function model() public function model()
{ {
return %ModelClass%::class; return %ModelClass%::class;
} }
/**
* 数据校验器
* @return mixed
*/
public function validator() public function validator()
{ {
return %ModelClass%Validator::class; return %ModelClass%Validator::class;
...@@ -47,7 +39,7 @@ class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelCla ...@@ -47,7 +39,7 @@ class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelCla
* 获取数据列表 * 获取数据列表
* @return array * @return array
*/ */
public function list(): array public function list()
{ {
$pageSize = (int)$this->request->input('page_size', DEFAULT_PAGE_SIZE); $pageSize = (int)$this->request->input('page_size', DEFAULT_PAGE_SIZE);
%list% %list%
...@@ -58,7 +50,7 @@ class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelCla ...@@ -58,7 +50,7 @@ class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelCla
* @param $id * @param $id
* @return array * @return array
*/ */
public function show($id): array public function show($id)
{ {
%show% %show%
} }
...@@ -68,7 +60,7 @@ class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelCla ...@@ -68,7 +60,7 @@ class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelCla
* @param array $attributes * @param array $attributes
* @return bool * @return bool
*/ */
public function create(array $attributes): bool public function create(array $attributes)
{ {
Db::transaction(function () use ($attributes) { Db::transaction(function () use ($attributes) {
%create% %create%
...@@ -82,7 +74,7 @@ class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelCla ...@@ -82,7 +74,7 @@ class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelCla
* @param $id * @param $id
* @return bool * @return bool
*/ */
public function update(array $attributes, $id): bool public function update(array $attributes, $id)
{ {
Db::transaction(function () use ($attributes, $id) { Db::transaction(function () use ($attributes, $id) {
%update% %update%
...@@ -96,10 +88,9 @@ class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelCla ...@@ -96,10 +88,9 @@ class %ModelClass%RepositoryEloquent extends BaseRepository implements %ModelCla
* @return bool * @return bool
* @throws HttpResponseException * @throws HttpResponseException
*/ */
public function delete($id): bool public function delete($id)
{ {
//已用外键做级联删除 和 删除验证,不需要做逻辑验证 return parent::delete($id); // TODO: Change the autogenerated stub
return $this->find($id)->delete();
} }
%rs% %rs%
} }
...@@ -16,6 +16,7 @@ use Meibuyu\Micro\Validator\HyperfValidator; ...@@ -16,6 +16,7 @@ use Meibuyu\Micro\Validator\HyperfValidator;
class %ModelClass%Validator extends HyperfValidator class %ModelClass%Validator extends HyperfValidator
{ {
protected $rules = [ protected $rules = [
ValidatorInterface::RULE_CREATE => [ ValidatorInterface::RULE_CREATE => [
%createRules% %createRules%
...@@ -29,8 +30,4 @@ class %ModelClass%Validator extends HyperfValidator ...@@ -29,8 +30,4 @@ class %ModelClass%Validator extends HyperfValidator
%attributes% %attributes%
]; ];
protected $messages = [
%messages%
];
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment