MakeModelCommand.php 51 KB
Newer Older
1 2 3 4 5 6 7 8
<?php

declare(strict_types=1);

namespace Meibuyu\Micro\Command;

use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
王源's avatar
王源 committed
9
use Hyperf\Contract\ContainerInterface;
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
use Hyperf\Database\ConnectionResolverInterface;
use Hyperf\Database\Schema\MySqlBuilder;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\Str;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

/**
 * @Command
 */
class MakeModelCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

王源's avatar
王源 committed
27 28
    private $path;
    private $appPath;
29

王源's avatar
王源 committed
30
    private $builder;
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

    private $table = "";
    private $tableIndex = 0;

    private $tables = [];

    private $allTableStructures = [];

    private $currentTableStructure = [];

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->path = __DIR__ . "/stubs/";
        $this->appPath = BASE_PATH . '/app/';
        $this->builder = $this->getSchemaBuilder();
        parent::__construct('mm');
    }

    /**
     * 获取数据库创建者
     * @return MySqlBuilder
     */
    protected function getSchemaBuilder(): MySqlBuilder
    {
        $resolver = $this->container->get(ConnectionResolverInterface::class);
        $connection = $resolver->connection();
        return $connection->getSchemaBuilder();
    }

    public function handle()
    {
        $this->initTableStructures();
        /*$this->info(print_r($this->allTableStructures, true));
        return false;*/
        $tables = [];
        $isAll = $this->input->getOption('database');
        $table = $this->input->getArgument('name');
        if (!$table && !$isAll) {
            $this->error("请输入表名进行单表生成 或者 -d 参数 进行全库生成,或使用 --help查看帮助");
            return false;
        }
        if ($this->input->getOption('database')) {
            $tables = $this->tables;
        } else {
            $tables[] = $this->getTable();
        }
        foreach ($tables as $k => $v) {
            if ($v == 'migrations') {
                continue;
            }
梁俊杰's avatar
梁俊杰 committed
82 83 84 85
            if (!$this->builder->hasTable($v)) {
                $this->info("表" . $v . "不存在!");
                continue;
            }
86 87 88 89 90 91 92 93
            $this->tableIndex = $k;
            $this->input->setArgument("name", $v);
            $this->table = $v;
            $this->currentTableStructure = $this->allTableStructures[$v];
            $this->info("开始生成:" . $v);
            if (!Str::contains($v, "_to_") && ($this->input->getOption('model') || $this->input->getOption('all'))) {
                $this->makeModel();
            }
94
            if (!Str::contains($v, "_to_") && ($this->input->getOption('controller') || $this->input->getOption('all'))) {
95 96 97 98
                $this->makeRepositoryInterface();
                $this->makeRepository();
                $this->makeController();
            }
99 100 101
            if (!Str::contains($v, "_to_") && ($this->input->getOption('validator') || $this->input->getOption('all'))) {
                $this->makeValidator();
            }
102 103 104
            if (!Str::contains($v, "_to_") && $this->input->getOption('seeder')) {
                $this->makeSeeder();
            }
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
            if ($this->input->getOption('migrate') || $this->input->getOption('all')) {
                $this->makeMigrate();
            }
        }
    }

    /**
     *获取表结构
     */
    private function initTableStructures()
    {
        //tables
        $tables = Db::select("select table_name,`engine`,table_comment from  information_schema.tables 
                  where table_schema=database()");
        $tables = array_map('get_object_vars', $tables);
        $tables = collect($tables)->keyBy("table_name")->toArray();

        //fields
        $fields = Db::select("select table_name,column_name,column_default,is_nullable,data_type,collation_name,column_type,column_key,extra,column_comment 
                  from information_schema.columns where table_schema=database()");
        $fieldList = array_map('get_object_vars', $fields);
        //对字段数据进行处理
        foreach ($fieldList as $fk => $fv) {
            $fieldList[$fk]['length'] = trim(str_replace([$fv['data_type'], "(", ")"], "", $fv['column_type']));
            //针对层级处理
            if ($fv['column_name'] == 'parent_id' || $fv['column_name'] == 'pid') {
                $relation = [];
                $relation['function'] = "parent";
                $relation['relation_model_name'] = Str::studly(Str::singular($fv['table_name']));
                $relation['relation_table'] = $fv['table_name'];
                $relation['relation_table_key'] = "id";
                $relation['local_table'] = $fv['table_name'];
                $relation['local_table_key'] = $fv['column_name'];
                $tables[$relation['local_table']]['relations']['belongsTo'][] = $relation;

                $reverseRelation = [];
                $reverseRelation['function'] = 'children';
                $reverseRelation['relation_model_name'] = $relation['relation_model_name'];
                $reverseRelation['relation_table'] = $relation['local_table'];
                $reverseRelation['relation_table_key'] = $relation['local_table_key'];
                $reverseRelation['local_table'] = $relation['relation_table'];
                $reverseRelation['local_table_key'] = $relation['relation_table_key'];
                $tables[$reverseRelation['relation_table']]['relations']['hasMany'][] = $reverseRelation;

            } else if (Str::endsWith($fv['column_name'], '_id')) {
                //关联表处理
                if (Str::contains($fv['table_name'], "_to_")) {
                    $ts = explode("_to_", $fv['table_name']);
                    $ts = collect($ts)->map(function ($item) {
                        return Str::plural($item);
                    })->all();
                    //$this->info(print_r($ts, true));
                    $relation = [];
                    if (Str::singular($ts[0]) . "_id" == $fv['column_name']) {
                        $relation['constraint_table'] = $ts[1];
                        $relation['constraint_table_key'] = Str::singular($ts[1]) . "_id";
                        $relation['local_table'] = $ts[0];
                    } else {
                        $relation['constraint_table'] = $ts[0];
                        $relation['constraint_table_key'] = Str::singular($ts[0]) . "_id";
                        $relation['local_table'] = $ts[1];
                    }
王源's avatar
王源 committed
167
                    $relation['local_table_key'] = $fv['column_name'];
168
                    $relation['relation_table'] = $fv['table_name'];
169
                    $relation['function'] = Str::snake($relation['constraint_table']);
170 171 172 173 174 175 176 177
                    $relation['relation_model_name'] = Str::studly(Str::singular($relation['constraint_table']));
                    $tables[$relation['local_table']]['relations']['belongsToMany'][] = $relation;
                } else {
                    $relation = [];
                    $relation['relation_table'] = Str::plural(Str::replaceLast("_id", "", $fv['column_name']));
                    if (!isset($tables[$relation['relation_table']])) {
                        continue;
                    }
178
                    $relation['function'] = Str::snake(Str::singular($relation['relation_table']));
179 180 181 182 183 184 185 186 187 188
                    $relation['relation_model_name'] = Str::studly(Str::singular($relation['relation_table']));
                    $relation['relation_table_key'] = "id";
                    $relation['local_table'] = $fv['table_name'];
                    $relation['local_table_key'] = $fv['column_name'];
                    $tables[$relation['local_table']]['relations']['belongsTo'][] = $relation;
                    $reverseRelation = [];
                    $reverseRelation['relation_table'] = $relation['local_table'];
                    $reverseRelation['relation_table_key'] = $relation['local_table_key'];
                    $reverseRelation['local_table'] = $relation['relation_table'];
                    $reverseRelation['local_table_key'] = $relation['relation_table_key'];
189
                    $reverseRelation['function'] = Str::snake($reverseRelation['relation_table']);
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
                    $reverseRelation['relation_model_name'] = Str::studly(Str::singular($reverseRelation['relation_table']));
                    $tables[$reverseRelation['local_table']]['relations']['hasMany'][] = $reverseRelation;
                }
            }
        }
        $fields = collect($fieldList)->groupBy("table_name")->toArray();

        //constraints
        $constraints = Db::select("select a.constraint_name,a.table_name,b.column_name,a.referenced_table_name,
                        b.referenced_column_name,a.update_rule,a.delete_rule
                        from information_schema.referential_constraints a,information_schema.key_column_usage b 
                        where a.constraint_schema=database() and a.constraint_schema=b.constraint_schema 
                        and a.table_name=b.table_name and a.constraint_name=b.constraint_name");
        $constraints = array_map('get_object_vars', $constraints);
        $constraints = collect($constraints)->groupBy("table_name")->toArray();

        //$indexes
        $indexes = Db::select("select table_name,non_unique,index_name,column_name 
              from information_schema.statistics where table_schema=database()");
        $indexes = array_map('get_object_vars', $indexes);
        $indexes = collect($indexes)->groupBy("table_name")->toArray();
        foreach ($tables as $k => $v) {
王源's avatar
王源 committed
212 213
            $v['fields'] = $fields[$k] ?? [];
            $v['constraints'] = $constraints[$k] ?? [];
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
            if (isset($indexes[$k])) {
                $v['indexes'] = collect($indexes[$k])->groupBy("index_name")->toArray();
            } else {
                $v['indexes'] = [];
            }
            $tables[$k] = $v;
        }
        $this->resortTable($tables);
        $this->allTableStructures = $tables;
    }

    private function resortTable($tables)
    {
        $done = false;
        while (!$done) {
            foreach ($tables as $k => $v) {
                if (!$v['constraints']) {
                    $this->tables[] = $k;
                    unset($tables[$k]);
                } else {
                    $p = true;
                    foreach ($v['constraints'] as $cs) {
                        if (!in_array($cs['referenced_table_name'], $this->tables) && $cs['referenced_table_name'] != $k) {
                            $p = false;
                            break;
                        }
                    }
                    if ($p) {
                        $this->tables[] = $k;
                        unset($tables[$k]);
                    }
                }
            }
            if (empty($tables)) {
                $done = true;
            }
        }
    }

    /**
     * 获取当前数据库表名
     * @return string
     */
    private function getTable(): string
    {
        return Str::lower(trim($this->input->getArgument('name')));
    }

    private function makeModel()
    {
        $stubFile = $this->path . 'model.stub';
        $folder = $this->appPath . 'Model';
        $this->makeFolder($folder);
        $table = $this->table;
        $modelName = Str::studly(Str::singular($table));
        $file = $folder . "/" . $modelName . ".php";
        $content = file_get_contents($stubFile);
        $info = $this->currentTableStructure;
        $filterFields = ["id", "created_at", "updated_at", "deleted_at"];
        $fillAble = '';
        $properties = '';
        $timestamps = 0;
        $softDelete = false;
        $list = $info['fields'];
王源's avatar
王源 committed
278
        foreach ($list as $v) {
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
            $name = $v['column_name'];
            $pc = [
                'bigint' => 'integer',
                'int' => 'integer',
                'tinyint' => 'integer',
                'smallint' => 'integer',
                'mediumint' => 'integer',
                'integer' => 'integer',
                'numeric' => 'integer',
                'float' => 'float',
                'real' => 'double',
                'double' => 'double',
                'decimal' => 'double',
                'bool' => 'bool',
                'boolean' => 'bool',
                'char' => 'string',
                'tinytext' => 'string',
                'text' => 'string',
                'mediumtext' => 'string',
                'longtext' => 'string',
                'year' => 'string',
                'varchar' => 'string',
                'string' => 'string',
                'enum' => 'array',
                'set' => 'array',
王源's avatar
王源 committed
304 305 306 307
                'date' => 'string',
                'datetime' => 'string',
                'custom_datetime' => 'string',
                'timestamp' => 'string',
308 309 310 311
                'collection' => 'collection',
                'array' => 'array',
                'json' => 'string',
            ];
王源's avatar
王源 committed
312
            $properties .= " * @property " . ($pc[$v['data_type']] ?? "string") . " $" . $name . ($v['column_comment'] ? " " . $v['column_comment'] : "") . "\n";
313
            if ($name == 'created_at' || $name == 'updated_at') {
314 315 316 317 318 319 320 321
                $timestamps++;
            }
            if ($name == 'deleted_at') {
                $softDelete = true;
            }
            if (in_array($name, $filterFields)) {
                continue;
            }
322
            $fillAble .= "\t\t'" . $name . "'," . "\n";
323 324 325 326 327 328
        }
        $relation = '';
        if (isset($info['relations']) && $info['relations']) {
            $relation .= "\n";
            if (isset($info['relations']['belongsTo'])) {
                foreach ($info['relations']['belongsTo'] as $v) {
王源's avatar
王源 committed
329 330
                    $relation .= "\n\t/**\n\t* 属于" . $v['relation_model_name'] . "的关联\n\t*/";
                    $relation .= "\n\tpublic function " . $v['function'] . "()";
331
                    $relation .= "\n\t{";
梁俊杰's avatar
梁俊杰 committed
332
                    $relation .= "\n\t\t" . 'return $this->belongsTo(' . $v['relation_model_name'] . "::class);";
333 334 335 336 337 338 339 340 341 342 343 344
                    $relation .= "\n\t}";
                    $properties .= " * @property " . $v['relation_model_name'] . " $" . $v['function'] . "\n";
                }
            }
            if (isset($info['relations']['belongsToMany'])) {
                foreach ($info['relations']['belongsToMany'] as $v) {
                    $relation .= "\n\t/**\n\t* 属于很多" . $v['relation_model_name'] . "的关联";
                    $relation .= "\n\t* @return \Hyperf\Database\Model\Relations\BelongsToMany";
                    $relation .= "\n\t**/";
                    $relation .= "\n\tpublic function " . $v['function'] . "()";
                    $relation .= "\n\t{";
                    $relation .= "\n\t\t" . 'return $this->belongsToMany(' . $v['relation_model_name'] . "::class,'"
梁俊杰's avatar
梁俊杰 committed
345
                        . $v['relation_table'] . "');";
346 347 348 349 350 351 352 353 354 355 356
                    $relation .= "\n\t}";
                    $properties .= " * @property " . $v['relation_model_name'] . "[] $" . $v['function'] . "\n";
                }
            }
            if (isset($info['relations']['hasMany'])) {
                foreach ($info['relations']['hasMany'] as $v) {
                    $relation .= "\n\t/**\n\t* 有很多" . $v['relation_model_name'] . "的关联";
                    $relation .= "\n\t* @return \Hyperf\Database\Model\Relations\HasMany";
                    $relation .= "\n\t**/";
                    $relation .= "\n\tpublic function " . $v['function'] . "()";
                    $relation .= "\n\t{";
梁俊杰's avatar
梁俊杰 committed
357
                    $relation .= "\n\t\t" . 'return $this->hasMany(' . $v['relation_model_name'] . "::class);";
358 359 360 361 362 363 364 365 366 367 368
                    $relation .= "\n\t}";
                    $properties .= " * @property " . $v['relation_model_name'] . "[] $" . $v['function'] . "\n";
                }
            }
        }
        $sd = '';
        $sdn = '';
        if ($softDelete) {
            $sd = "use SoftDeletes;\n";
            $sdn = "use Hyperf\Database\Model\SoftDeletes;\n";
        }
王源's avatar
王源 committed
369 370
        $patterns = ['%namespace%', "%ClassName%", "%fillAble%", '%relations%', '%timestamps%', '%properties%', '%SoftDelete%'];
        $replacements = [$sdn, $modelName, $fillAble, $relation, ($timestamps == 2 ? 'true' : 'false'), $properties, $sd];
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397

        $content = $this->buildField($patterns, $replacements, $content);
        $this->writeToFile($file, $content);
    }

    /**
     * 创建目录
     * @param $folder
     */
    private function makeFolder($folder)
    {
        if (!file_exists($folder)) {
            @mkdir($folder, 0777, true);
        }
    }

    /**
     * 替换文件内容
     * @param array $patterns 被替换的字符数组
     * @param array $replacements 替换的字符数组
     * @param string $content 文件原始内容
     * @return string
     */
    private function buildField(array $patterns, array $replacements, string $content): string
    {
        $author = $this->input->getOption("author");
        $patterns = array_merge($patterns, ['%user%', '%date%', '%time%']);
王源's avatar
王源 committed
398
        $replacements = array_merge($replacements, [$author ?: "Auto generated.", date("Y-m-d"), date("h:i:s")]);
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
        return str_replace($patterns, $replacements, $content);
    }

    /**
     * 把内容写入文件
     * @param string $file 文件路径和文件名
     * @param string $content 文件内容
     * @return bool 创建是否成功
     */
    private function writeToFile(string $file, string $content): bool
    {
        $force = $this->input->getOption("force");
        if (!$force && file_exists($file)) {
            return false;
        }
        file_put_contents($file, $content);
        $file = pathinfo($file, PATHINFO_FILENAME);
王源's avatar
王源 committed
416
        $this->info("<info>[INFO] Created File:</info> $file");
417 418 419
        return true;
    }

王源's avatar
王源 committed
420
    private function makeRepositoryInterface()
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
    {
        $stubFile = $this->path . 'repositoryInterface.stub';
        $folder = $this->appPath . '/Repository/Interfaces';
        $this->makeFolder($folder);
        $table = $this->table;
        $className = Str::studly(Str::singular($table)) . "Repository";
        $file = $folder . "/" . $className . ".php";
        $content = file_get_contents($stubFile);

        $patterns = ["%ClassName%"];
        $replacements = [$className];
        $content = $this->buildField($patterns, $replacements, $content);
        $this->writeToFile($file, $content);
    }

    private function makeRepository()
    {
        $stubFile = $this->path . 'repository.stub';
        $folder = $this->appPath . '/Repository/Eloquent';
        $this->makeFolder($folder);

        $table = $this->table;
        $modelClass = Str::studly(Str::singular($table));
        $className = $modelClass . "RepositoryEloquent";
        $file = $folder . "/" . $className . ".php";
        $content = file_get_contents($stubFile);
        $info = $this->currentTableStructure;
        //列表
449
        $list = "\$conditions = \$this->request->all();\n";
450 451 452
        $list .= "\t\t\$list = \$this->model->where(function (\$q) use (\$conditions) {\n";
        foreach ($info['fields'] as $v) {
            if (Str::endsWith($v['column_name'], "_id")) {
梁俊杰's avatar
梁俊杰 committed
453
                $list .= "\t\t\tif(isset(\$conditions['" . $v['column_name'] . "']) && \$conditions['" . $v['column_name'] . "'] !== '') {\n";
454 455 456
                $list .= "\t\t\t\t\$q->where('" . $v['column_name'] . "', \$conditions['" . $v['column_name'] . "']);\n";
                $list .= "\t\t\t}\n";
            } else if ($v['column_name'] == 'name' || Str::contains($v['column_name'], "_name")) {
梁俊杰's avatar
梁俊杰 committed
457
                $list .= "\t\t\tif(isset(\$conditions['" . $v['column_name'] . "']) && \$conditions['keyword'] !== '') {\n";
458 459 460 461 462 463 464 465
                $list .= "\t\t\t\t\$q->where('" . $v['column_name'] . "', \$conditions['keyword']);\n";
                $list .= "\t\t\t}\n";
            }
        }
        $list .= "\t\t})";
        //显示
        $show = "\$info = \$this->model\n";
        //新增
王源's avatar
王源 committed
466
        $create = "/** @var $modelClass \$model */\n \t\t\t\$model = parent::create(\$attributes);\n";
467
        //新增
王源's avatar
王源 committed
468
        $update = "/** @var $modelClass \$model */\n \t\t\t\$model = parent::update(\$attributes, \$id);\n";
469 470 471 472 473 474 475 476 477 478
        //删除
        $delete = '';
        //关联查询
        $rs = "";
        if (isset($info['relations']) && $info['relations']) {
            if (isset($info['relations']) && $info['relations']) {
                if (isset($info['relations']['belongsTo'])) {
                    $list .= "\n\t\t->with([";
                    $show .= "\n\t\t->with([";
                    $t = [];
王源's avatar
王源 committed
479
                    foreach ($info['relations']['belongsTo'] as $v) {
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
                        $x = "\n\t\t\t'" . $v['function'] . "' => function (\$q) {\n";
                        $fields = $this->listColumns($v['relation_table']);
                        $fields = collect($fields['fields'])->keyBy('column_name')
                            ->forget(['created_at', 'updated_at', 'deleted_at'])->pluck('column_name')->toArray();
                        $fields = join("','", $fields);
                        $x .= "\t\t\t\t\$q->select(['" . $fields . "']);\n";
                        $x .= "\t\t\t}";
                        $t[] = $x;
                    }
                    $t = join(",", $t) . "])";
                    $list .= $t;
                    $show .= $t;
                }
                if (isset($info['relations']['belongsToMany'])) {
                    $list .= "\n\t\t->with([";
                    $show .= "\n\t\t->with([";
                    $t = [];
                    foreach ($info['relations']['belongsToMany'] as $v) {
                        $x = "\n\t\t\t'" . $v['function'] . "' => function (\$q) {\n";
                        $fields = $this->listColumns($v['constraint_table']);
                        $fields = collect($fields['fields'])->keyBy('column_name')
                            ->forget(['created_at', 'updated_at', 'deleted_at'])->pluck('column_name')->toArray();
                        $fields = join("','", $fields);
                        $x .= "\t\t\t\t\$q->select(['" . $fields . "'])->orderByDesc('id')->limit(20);\n";
                        $x .= "\t\t\t}";
                        $t[] = $x;

                        $create .= "\t\t\tisset(\$attributes['" . $v['constraint_table_key'] . "s']) && \$model->{$v['function']}()->sync(\$attributes['" . $v['constraint_table_key'] . "s']);\n";
                        $update .= "\t\t\tisset(\$attributes['" . $v['constraint_table_key'] . "s']) && \$model->{$v['function']}()->sync(\$attributes['" . $v['constraint_table_key'] . "s']);\n";
                    }
                    $t = join(",", $t) . "])";
                    $list .= $t;
                    $show .= $t;
                }
                if (isset($info['relations']['hasMany'])) {
                    foreach ($info['relations']['hasMany'] as $v) {
516
                        $f = Str::camel($v['function']);
王源's avatar
王源 committed
517
                        $rs .= "\n\tpublic function $f(\$id): array\n";
518
                        $rs .= "\t{\n";
王源's avatar
王源 committed
519
                        $rs .= "\t\t\$pageSize = (int)\$this->request->input('page_size', DEFAULT_PAGE_SIZE);\n";
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
                        $rs .= "\t\treturn \$this->find(\$id)->{$v['function']}()->orderByDesc('id')->paginate(\$pageSize)->toArray();\n";
                        $rs .= "\t}\n";
                    }
                }
            }
        }
        $list .= "\n\t\t->paginate(\$pageSize)\n";
        $list .= "\t\t->toArray();\n";
        $list .= "\t\treturn \$list;";
        $show .= "\n\t\t->find(\$id)\n\t\t->toArray();\n";
        $show .= "\t\treturn \$info;";


        $patterns = ["%ModelClass%", "%list%", "%show%", "%create%", "%update%", "%delete%", "%rs%"];
        $replacements = [$modelClass, $list, $show, $create, $update, $delete, $rs];
        $content = $this->buildField($patterns, $replacements, $content);
        $this->writeToFile($file, $content);
        $this->addDepends($modelClass);
    }

    private function listColumns($table)
    {
        $table = trim($table);
王源's avatar
王源 committed
543
        return $this->allTableStructures[$table] ?? [];
544 545 546 547 548 549 550 551 552 553 554 555
    }

    /**
     * 添加类到依赖注入配置文件
     * @param $modelClass
     */
    private function addDepends($modelClass)
    {
        $file = BASE_PATH . '/config/autoload/dependencies.php';
        if (file_exists($file)) {
            $content = file_get_contents($file);
            if (strpos($content, "\App\Repository\Interfaces\\" . $modelClass . "Repository::class") !== false) {
王源's avatar
王源 committed
556
                return;
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
            }
            $content = str_replace("]", "    \\App\\Repository\\Interfaces\\" . $modelClass . "Repository::class => \\App\\Repository\\Eloquent\\" . $modelClass . "RepositoryEloquent::class,\n]", $content);
            $this->writeToFile($file, $content);
        }
    }

    private function makeController()
    {
        $stubFile = $this->path . 'controller.stub';
        $folder = $this->appPath . '/Controller';
        $this->makeFolder($folder);

        $table = $this->table;
        $modelClass = Str::studly(Str::singular($table));
        $className = $modelClass . "Controller";
        $file = $folder . "/" . $className . ".php";
        $content = file_get_contents($stubFile);

        $info = $this->currentTableStructure;
        //关联查询
        $rs = "";
        $routes = [];
        if (isset($info['relations']) && $info['relations']) {
            if (isset($info['relations']) && $info['relations']) {
                if (isset($info['relations']['hasMany'])) {
                    foreach ($info['relations']['hasMany'] as $v) {
583
                        $f = Str::camel($v['function']);
584 585 586 587 588 589
                        $rs .= "\n\t/**";
                        $rs .= "\n\t * 获取{$v['relation_model_name']}关联列表数据";
                        $rs .= "\n\t * @Perm(\"index\")";
                        $rs .= "\n\t * @param; \$id id编号";
                        $rs .= "\n\t * @return mixed";
                        $rs .= "\n\t */";
王源's avatar
王源 committed
590
                        $rs .= "\n\tpublic function $f(\$id)\n";
591
                        $rs .= "\t{\n";
王源's avatar
王源 committed
592
                        $rs .= "\t\t\$data = \$this->repository->$f(\$id);\n";
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
                        $rs .= "\t\treturn success('获取成功', \$data);\n";
                        $rs .= "\t}\n";
                        $routes[] = $v['function'];
                    }
                }
            }
        }

        $patterns = ["%ModelClass%", "%rs%"];
        $replacements = [$modelClass, $rs];
        $content = $this->buildField($patterns, $replacements, $content);
        $this->writeToFile($file, $content);
        $this->addRoutes($modelClass, $routes);
    }

王源's avatar
王源 committed
608 609
    /**
     * 添加Controller到路由类
610
     * @param $modelClass
王源's avatar
王源 committed
611
     * @param array $routes
612 613 614 615 616 617 618 619 620
     */
    private function addRoutes($modelClass, $routes = [])
    {
        $file = BASE_PATH . '/config/routes.php';
        if (file_exists($file)) {
            $table = $this->table;
            $content = file_get_contents($file);
            $group = str_replace("_", "/", Str::snake($table));
            if (strpos($content, "Router::addGroup('" . $group . "', function () {") !== false) {
王源's avatar
王源 committed
621
                return;
622 623
            }
            $info = $this->currentTableStructure;
梁俊杰's avatar
梁俊杰 committed
624
            $tableComment = (isset($info['table_comment']) && $info['table_comment']) ? $info['table_comment'] : $table;
625 626 627
            $content .= "\n\t// " . $tableComment;
            $content .= "\n\tRouter::addGroup('" . $group . "', function () {";
            $content .= "\n\t\tRouter::get('', 'App\Controller\\" . $modelClass . "Controller@index');";
王源's avatar
王源 committed
628
            $content .= "\n\t\tRouter::get('/{id:\d+}', 'App\Controller\\" . $modelClass . "Controller@show');";
629
            $content .= "\n\t\tRouter::post('', 'App\Controller\\" . $modelClass . "Controller@create');";
王源's avatar
王源 committed
630 631
            $content .= "\n\t\tRouter::patch('/{id:\d+}', 'App\Controller\\" . $modelClass . "Controller@update');";
            $content .= "\n\t\tRouter::delete('/{id:\d+}', 'App\Controller\\" . $modelClass . "Controller@delete');";
632 633
            if ($routes) {
                foreach ($routes as $v) {
王源's avatar
王源 committed
634
                    $content .= "\n\t\tRouter::get('/$v/{id:\d+}', 'App\Controller\\" . $modelClass . "Controller@$v');";
635 636 637 638 639 640 641
                }
            }
            $content .= "\n\t});";
            $this->writeToFile($file, $content);
        }
    }

642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
    /**
     * 创建验证文件
     */
    private function makeValidator()
    {
        $stubFile = $this->path . 'validator.stub';
        $folder = $this->appPath . '/Validators';
        $this->makeFolder($folder);
        $table = $this->table;
        $modelClass = Str::studly(Str::singular($table));
        $className = $modelClass . "Validator";
        $file = $folder . "/" . $className . ".php";
        $content = file_get_contents($stubFile);
        $info = $this->currentTableStructure;
        $filterFields = ["id", "created_at", "updated_at", "deleted_at"];
        $rules = '';
        $attributes = '';
        $list = $info['fields'];
        foreach ($list as $v) {
            $name = $v['column_name'];
            $default = $v['column_default'];
            $type = $v['data_type'];
            $key = $v['column_key'];
            $null = $v['is_nullable'];
            $comment = $v['column_comment'];
            $length = $v['length'];
            if (in_array($name, $filterFields)) {
                continue;
            }
            $rs = [];
            $required = "nullable";
            if ($null !== 'YES') {
王源's avatar
王源 committed
674
                if ($default !== '' && $default !== '0' && !$default) {
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
                    $required = "required";
                }
            }
            $rs[] = $required;
            switch ($type) {
                case "bigint":
                case "smallint":
                case "tinyint":
                case "mediumint":
                case "int":
                case "integer":
                    $rs[] = 'integer';
                    break;
                case "decimal":
                case "double":
                case "float":
                case "numeric":
                case "real":
                    $rs[] = 'numeric';
                    break;
                case "char":
                case "varchar":
                case "tinytext":
                case "mediumtext":
                case "longtext":
                case "text":
                    $rs[] = 'string';
                    if ($length) {
                        $rs[] = 'max:' . $length;
                    }
                    break;
                case "date":
                case "datetime":
                case "time":
                case "timestamp":
                case "year":
                    $rs[] = 'date';
                    break;
                case "enum":
                case "set":
                    $rs[] = 'in:[' . $length . "]";
                    break;
                default:
                    if (Str::contains($name, "email") || Str::contains($name, "e-mail") || Str::contains($name, "e_mail")) {
                        $rs[] = 'email';
                    } elseif ($name == 'url'
                        || Str::contains($name, "_url")
                        || Str::contains($name, "url_")) {
                        $rs[] = 'url';
                    } elseif ($name == 'date'
                        || Str::contains($name, "_date")
                        || Str::contains($name, "date_")) {
                        $rs[] = 'date';
                    }
                    break;
            }

            if ($key == 'uni') {
                $rs[] = "unique:$table," . $name;
            }
            if ($comment) {
                $attributes .= "\t\t'" . $name . "' => '" . $comment . "'," . "\n";
            }
            $rules .= "\t\t\t'" . $name . "' => '" . implode("|", $rs) . "'," . ($comment ? "// " . $comment . "-" . $type : "//" . $type) . "\n";
        }
王源's avatar
王源 committed
740
        $patterns = ["%ModelClass%", '%createRules%', '%updateRules%', '%attributes%'];
741 742 743
        $createRules = $rules;
        $updateRules = str_replace("nullable", "sometimes|nullable", $rules);
        $updateRules = str_replace("required", "sometimes|required", $updateRules);
王源's avatar
王源 committed
744
        $replacements = [$modelClass, $createRules, $updateRules, $attributes];
745 746 747 748
        $content = $this->buildField($patterns, $replacements, $content);
        $this->writeToFile($file, $content);
    }

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
    private function makeSeeder()
    {
        $stubFile = $this->path . 'seeder.stub';
        $folder = BASE_PATH . '/seeders/seeders/';
        $this->makeFolder($folder);
        $table = $this->table;
        $modelClass = Str::studly(Str::singular($table));
        $className = Str::studly($table) . "TableSeeder";
        $file = $folder . "/" . $table . "_table_seeder.php";
        $content = file_get_contents($stubFile);
        $info = $this->currentTableStructure;
        $filterFields = ["id"];
        $fields = [];
        $otherModel = [];
        $generateCount = $this->input->getOption("seeder");
王源's avatar
王源 committed
764
        $generateCount = $generateCount ?: 30;
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
        $otherProcess = "";
        $list = $info['fields'];
        $maxNumber = 4;
        foreach ($list as $v) {
            $name = $v['column_name'];
            $type = $v['data_type'];
            $length = explode(" ", $v['length']);
            if (in_array($name, $filterFields)) {
                continue;
            }

            switch ($type) {
                case "bigint":
                case "smallint":
                case "tinyint":
                case "mediumint":
                case "int":
                case "integer":
                    if ($name == "sex") {
王源's avatar
王源 committed
784
                        $fields[] = "\t\t\t\t'$name' => \$faker->randomElement([0,1]),";
785
                    } else if (Str::contains($name, "status")) {
王源's avatar
王源 committed
786
                        $fields[] = "\t\t\t\t'$name' => \$faker->randomDigit,";
787 788 789 790 791 792
                    } else if (Str::endsWith($name, "_id")) {
                        $o = str_replace("_id", "", $name);
                        $os = Str::plural($o);
                        if (in_array($os, $this->tables)) {
                            $o = Str::studly($o);
                            $otherModel[] = "\nuse App\Model\\" . $o . ";";
王源's avatar
王源 committed
793
                            $fields[] = "\t\t\t\t'$name' => $o::orderBy(Db::raw('rand()'))->first()->id,";
794 795 796
                        } else {
                            $n = ((isset($length[0]) && $length[0] && $length[0] < $maxNumber) ? $length[0] : $maxNumber);
                            $n = rand(1, $n);
王源's avatar
王源 committed
797
                            $fields[] = "\t\t\t\t'$name' => \$faker->randomNumber($n),";
798 799 800 801
                        }
                    } else {
                        $n = ((isset($length[0]) && $length[0] < $maxNumber) ? $length[0] : $maxNumber);
                        $n = rand(1, $n);
王源's avatar
王源 committed
802
                        $fields[] = "\t\t\t\t'$name' => \$faker->randomNumber($n),";
803 804 805 806 807 808 809 810 811 812
                    }
                    break;
                case "decimal":
                case "double":
                case "float":
                case "numeric":
                case "real":
                    $n = ((isset($length[0]) && $length[0] && $length[0] < $maxNumber) ? $length[0] : $maxNumber);
                    $n = rand(1, $n);
                    $n2 = ((isset($length[1]) && $length[1] < $maxNumber) ? $length[1] : 2);
王源's avatar
王源 committed
813
                    $n3 = $n2 + 20;
王源's avatar
王源 committed
814
                    $fields[] = "\t\t\t\t'$name' => \$faker->randomFloat($n,$n2,$n3),";
815 816 817 818
                    break;
                case "char":
                case "varchar":
                    $n = ((isset($length[0]) && $length[0]) ? $length[0] : 255);
王源's avatar
王源 committed
819 820
                    if ($name == "ip" || $name == "ip_address" || $name == "ip_addr") {
                        $fields[] = "\t\t\t\t'$name' => \$faker->ipv4,";
821
                    } else if (Str::contains($name, "email")) {
王源's avatar
王源 committed
822
                        $fields[] = "\t\t\t\t'$name' => \$faker->email,";
823
                    } else if ($name == "userName" || $name == "user_name" || $name == "uname") {
王源's avatar
王源 committed
824
                        $fields[] = "\t\t\t\t'$name' => \$faker->userName,";
825
                    } else if ($name == "url" || $name == "domain" || Str::endsWith($name, "_url") || Str::startsWith($name, "url_")) {
王源's avatar
王源 committed
826
                        $fields[] = "\t\t\t\t'$name' => \$faker->url,";
827
                    } else if ($name == "company" || $name == "company_name") {
王源's avatar
王源 committed
828
                        $fields[] = "\t\t\t\t'$name' => \$faker->company,";
829
                    } else if ($name == "gender") {
王源's avatar
王源 committed
830
                        $fields[] = "\t\t\t\t'$name' => \$faker->title(),";
831
                    } else if ($name == "name") {
王源's avatar
王源 committed
832
                        $fields[] = "\t\t\t\t'$name' => \$faker->name(),";
833
                    } else if (Str::contains($name, "city")) {
王源's avatar
王源 committed
834
                        $fields[] = "\t\t\t\t'$name' => \$faker->city,";
835
                    } else if (Str::contains($name, "street") || Str::contains($name, "address")) {
王源's avatar
王源 committed
836
                        $fields[] = "\t\t\t\t'$name' => \$faker->streetAddress,";
837
                    } else if (Str::contains($name, "postcode")) {
王源's avatar
王源 committed
838
                        $fields[] = "\t\t\t\t'$name' => \$faker->postcode,";
839
                    } else if (Str::contains($name, "country")) {
王源's avatar
王源 committed
840
                        $fields[] = "\t\t\t\t'$name' => \$faker->country,";
841
                    } else if (Str::contains($name, "phoneNumber") || $name == "tel" || $name == "mobile" || Str::contains($name, "phone")) {
王源's avatar
王源 committed
842
                        $fields[] = "\t\t\t\t'$name' => \$faker->phoneNumber,";
843
                    } else if (Str::contains($name, "color")) {
王源's avatar
王源 committed
844
                        $fields[] = "\t\t\t\t'$name' => \$faker->colorName,";
845
                    } else if (Str::contains($name, "image") || Str::contains($name, "path")) {
王源's avatar
王源 committed
846
                        $fields[] = "\t\t\t\t'$name' => \$faker->imageUrl(640, 480),";
847
                    } else if ($name == "ean" || $name == "bar_code") {
王源's avatar
王源 committed
848
                        $fields[] = "\t\t\t\t'$name' => \$faker->ean13,";
849
                    } else if ($n < 10) {
王源's avatar
王源 committed
850
                        $fields[] = "\t\t\t\t'$name' => \$faker->word,";
851
                    } elseif ($n < 100) {
王源's avatar
王源 committed
852
                        $fields[] = "\t\t\t\t'$name' => \$faker->sentence(6),";
853 854
                    } else {
                        $n = rand(2, 5);
王源's avatar
王源 committed
855
                        $fields[] = "\t\t\t\t'$name' => \$faker->paragraph($n, true),";
856 857 858 859 860 861
                    }
                    break;
                case "tinytext":
                case "mediumtext":
                case "longtext":
                case "text":
王源's avatar
王源 committed
862
                    $fields[] = "\t\t\t\t'$name' => \$faker->text,";
863 864
                    break;
                case "date":
王源's avatar
王源 committed
865
                    $fields[] = "\t\t\t\t'$name' => \$faker->date('Y-m-d'),";
866 867
                    break;
                case "datetime":
王源's avatar
王源 committed
868
                    $fields[] = "\t\t\t\t'$name' => \$faker->date('Y-m-d').' '.\$faker->time('H:i:s'),";
869 870
                    break;
                case "time":
王源's avatar
王源 committed
871
                    $fields[] = "\t\t\t\t'$name' => \$faker->time('H:i:s'),";
872 873
                    break;
                case "timestamp":
梁俊杰's avatar
梁俊杰 committed
874
                    if ($name == 'created_at' || $name == 'updated_at' || $name == 'deleted_at') {
王源's avatar
王源 committed
875
                        $fields[] = "\t\t\t\t'$name' => \$faker->date('Y-m-d').' '.\$faker->time('H:i:s'),";
梁俊杰's avatar
梁俊杰 committed
876
                    } else {
王源's avatar
王源 committed
877
                        $fields[] = "\t\t\t\t'$name' => \$faker->unixTime(),";
梁俊杰's avatar
梁俊杰 committed
878
                    }
879 880
                    break;
                case "year":
王源's avatar
王源 committed
881
                    $fields[] = "\t\t\t\t'$name' => \$faker->year(),";
882 883 884 885
                    break;
                case "enum":
                case "set":
                    $n = implode(",", $length);
王源's avatar
王源 committed
886
                    $fields[] = "\t\t\t\t'$name' => \$faker->randomElement([$n]),";
887 888
                    break;
                default:
王源's avatar
王源 committed
889
                    $fields[] = "\t\t\t\t'$name' => \$faker->word,";
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
                    break;
            }
        }
        $fields = join("\n", $fields);
        $otherModel = join("", $otherModel);
        $patterns = ["%modelClass%", '%className%', '%otherModel%', '%generateCount%', '%fields%', '%otherProcess%'];
        $replacements = [$modelClass, $className, $otherModel, $generateCount, $fields, $otherProcess];
        $content = $this->buildField($patterns, $replacements, $content);
        $this->writeToFile($file, $content);
        $this->addSeeder();
    }

    private function addSeeder()
    {
        $stubFile = $this->path . 'databaseSeeder.stub';
        $folder = BASE_PATH . '/seeders/';
        $file = $folder . "/DatabaseSeeder.php";
        if (!file_exists($file)) {
            $content = file_get_contents($stubFile);
            $this->writeToFile($file, $content);
        }
        $content = file_get_contents($file);
        if (strpos($content, Str::studly($this->table) . "TableSeeder::class") !== false) {
王源's avatar
王源 committed
913
            return;
914 915 916 917 918
        }
        $content = str_replace("];", "\t\t\t" . Str::studly($this->table) . "TableSeeder::class,\n\t\t];", $content);
        $this->writeToFile($file, $content);
    }

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
    private function makeMigrate()
    {
        $stubFile = $this->path . 'migration.stub';
        $folder = BASE_PATH . '/migrations';
        $this->makeFolder($folder);

        $table = $this->table;
        $className = "Create" . Str::studly($table) . "Table";
        $file = $folder . "/" . $this->getDatePrefix() . "_" . $this->tableIndex . "_create_" . $table . "_table.php";
        $content = file_get_contents($stubFile);
        $info = $this->currentTableStructure;
        $attributes = [];
        $timestamps = 0;
        //$b = new Blueprint('test');
        $softDelete = false;
        $pri = false;
        //生成字段
        foreach ($info['fields'] as $v) {
            $name = $v['column_name'];
            $default = $v['column_default'];
            $type = $v['data_type'];
            $collation = $v['collation_name'];
            $null = $v['is_nullable'];
            $extra = $v['extra'];
            $comment = $v['column_comment'];
            $length = $v['length'];
            if ($name == 'updated_at' || $name == 'created_at') {
                $timestamps++;
            } elseif ($name == 'deleted_at') {
                $softDelete = true;
            } else {
                $t = "\t\t\t\$table->";
                switch ($type) {
                    case "bigint":
                    case "smallint":
                    case "tinyint":
                    case "mediumint":
                    case "int":
                    case "integer":
                        if ($type == 'int' || $type == 'integer') {
                            $t .= "integer('" . $name . "'";
                        } else {
                            $t .= str_replace("int", "", $type) . "Integer('" . $name . "'";
                        }
                        if ($extra == 'auto_increment') {
                            $pri = true;
                            $t .= ", true";
                        } else {
                            $t .= ", false";
                        }
                        if ($length && strpos($length, "unsigned") !== false) {
                            $t .= ", true";
                        }
                        $t .= ")";
                        break;
                    case "decimal":
                    case "double":
                    case "float":
                    case "numeric":
                    case "real":
                        $tc = [
                            'numeric' => 'decimal',
                            'real' => 'double',
                        ];
王源's avatar
王源 committed
983
                        $t .= ($tc[$type] ?? $type) . "('" . $name . "'";
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
                        if ($length) {
                            $length = explode(" ", $length);
                            $length = explode(",", $length[0]);
                            $t .= ", " . $length[0] . ", " . $length[1];
                        }
                        $t .= ")";
                        break;
                    case "char":
                    case "varchar":
                    case "tinytext":
                    case "mediumtext":
                    case "longtext":
                    case "desc":
                    case "bit":
                    case "boolean":
                    case "text":
                        $tc = [
                            'char' => 'char',
                            'varchar' => 'string',
                            'desc' => 'text',
                            'tinytext' => 'text',
                            'text' => 'text',
                            'bit' => 'boolean',
                            'boolean' => 'boolean',
                            'longtext' => 'longText',
                            'mediumtext' => 'mediumText',
                        ];
                        $t .= $tc[$type] . "('" . $name . "'";
                        if ($length) {
                            $t .= ", " . $length;
                        }
                        $t .= ")";
                        break;
                    case "date":
                    case "datetime":
                    case "time":
                    case "timestamp":
                    case "year":
                        $tc = [
                            'datetime' => 'dateTime',
                        ];
王源's avatar
王源 committed
1025
                        $t .= ($tc[$type] ?? $type) . "('" . $name . "')";
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
                        break;
                    case "binary":
                    case "varbinary":
                    case "longblob":
                    case "blob":
                    case "mediumblob":
                    case "tinyblob":
                        $t .= "binary('" . $name . "')";
                        break;
                    case "enum":
                    case "set":
                        $tc = [
                            'set' => 'enum',
                        ];
王源's avatar
王源 committed
1040
                        $t .= ($tc[$type] ?? $type) . "('" . $name . "'";
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
                        $t .= ", [{
                            $length}])";
                        break;
                    case "geometry":
                    case "geometrycollection":
                    case "json":
                    case "jsonb":
                    case "point":
                    case "polygon":
                    case "linestring":
                    case "multipoint":
                    case "multipolygon":
                    case "multilinestring":
                        $tc = [
                            'geometrycollection' => 'geometryCollection',
                            'linestring' => 'lineString',
                            'multipoint' => 'multiPoint',
                            'multipolygon' => 'multiPolygon',
                            'multilinestring' => 'multiLineString',
                        ];
王源's avatar
王源 committed
1061
                        $t .= ($tc[$type] ?? $type) . "('" . $name . "'";
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
                        if ($length) {
                            $t .= ", " . $length;
                        }
                        $t .= ")";
                        break;
                    default:
                        $t = '';
                        break;
                }
                if ($t) {
1072 1073
                    if ($null == 'YES') {
                        $t .= "->nullable()";
1074
                    }
王源's avatar
王源 committed
1075
                    if (($default && $default !== '') || $default === '0') {
1076 1077 1078
                        if ($type !== 'timestamp') {
                            $t .= "->default('$default')";
                        }
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
                    }
                    if ($collation) {
                        $t .= "->collation('$collation')";
                    }
                    if ($comment) {
                        $t .= "->comment('$comment')";
                    }
                    $t .= ";";
                    $attributes[] = $t;
                }
            }
        }
        if ($timestamps == 2) {
            $attributes[] = "\t\t\t\$table->timestamps();";
        }
        if ($softDelete) {
            $attributes[] = "\t\t\t\$table->softDeletes();";
        }
        //主键及索引
        if ($info['indexes']) {
            foreach ($info['indexes'] as $k => $v) {
                $fields = collect($v)->pluck("column_name")->all();
                $fields = implode("','", $fields);
                if ($k == 'PRIMARY') {
                    if (!$pri) {
王源's avatar
王源 committed
1104
                        $attributes[] = "\t\t\t\$table->primary(['$fields']);";
1105 1106 1107
                    }
                } else {
                    if ($v[0]['non_unique'] === 0) {
王源's avatar
王源 committed
1108
                        $attributes[] = "\t\t\t\$table->unique(['$fields'], '$k');";
1109
                    } else {
王源's avatar
王源 committed
1110
                        $attributes[] = "\t\t\t\$table->index(['$fields'], '$k');";
1111 1112 1113 1114 1115 1116
                    }
                }
            }
        }
        //外键
        if ($info['constraints']) {
王源's avatar
王源 committed
1117
            foreach ($info['constraints'] as $v) {
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
                $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']) {
                    $t .= "->onDelete('{$v['delete_rule']}')";
                }
                /*if ($v['update_rule']) {
                    $t .= "->onUpdate('{$v['update_rule']}')";
                }*/
                $attributes[] = $t . ";";
            }
        }
        $attributes = implode("\n", $attributes);
        $tableComment = "";
梁俊杰's avatar
梁俊杰 committed
1130
        if (isset($info['table_comment']) && $info['table_comment']) {
1131 1132
            $tableComment = 'Db::statement("alter table `' . $table . '` comment \'' . $info['table_comment'] . '\'");';
        }
王源's avatar
王源 committed
1133
        $patterns = ["%ClassName%", '%tableName%', '%attributes%', '%tableComment%'];
1134 1135 1136 1137 1138 1139 1140 1141 1142
        $replacements = [$className, $table, $attributes, $tableComment];
        $content = $this->buildField($patterns, $replacements, $content);
        $this->writeToFile($file, $content);

    }

    /**生成迁移文件的日期格式
     * @return string
     */
王源's avatar
王源 committed
1143
    private function getDatePrefix(): string
1144 1145 1146 1147
    {
        return date('Y_m_dHis');
    }

王源's avatar
王源 committed
1148
    public function configure()
1149 1150 1151 1152 1153 1154
    {
        parent::configure();
        $this->addOption('all', 'a', InputOption::VALUE_NONE, '生成所有文件');
        $this->addOption('model', 'm', InputOption::VALUE_NONE, '生成model文件');
        $this->addOption('controller', 'c', InputOption::VALUE_NONE, '生成controller文件');
        $this->addOption('migrate', 'i', InputOption::VALUE_NONE, '生成迁移文件');
1155
        $this->addOption('validator', 'l', InputOption::VALUE_NONE, '生成验证文件');
1156 1157
        $this->addOption('author', 'r', InputOption::VALUE_OPTIONAL, '文件作者,后面可跟空格名字,表示生成的文件作者');
        $this->addOption('seeder', 's', InputOption::VALUE_OPTIONAL, '生成数据填充文件,后面可跟空格数字,表示生成的数据量');
1158 1159 1160 1161 1162 1163 1164 1165 1166
        $this->addOption('force', 'f', InputOption::VALUE_NONE, '文件存在是否覆盖');
        $this->addOption('database', 'd', InputOption::VALUE_NONE, '全数据库索引自动生成全站文件');
        $this->setDescription('根据数据表生成model文件和迁移文件和控制器');
    }

    /**
     * 配置文件内容
     * @return array
     */
王源's avatar
王源 committed
1167
    protected function getArguments()
1168 1169 1170 1171 1172 1173
    {
        return [
            ['name', InputArgument::OPTIONAL, '数据库表名'],
        ];
    }
}