MakeModelCommand.php 54.4 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 27 28 29 30 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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
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;

    private $path = '';
    private $appPath = '';

    private $builder = null;

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

    private $tables = [];

    private $allTableStructures = [];

    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)
    {
        $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
116 117 118 119
            if (!$this->builder->hasTable($v)) {
                $this->info("表" . $v . "不存在!");
                continue;
            }
120 121 122 123 124 125 126 127
            $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();
            }
128
            if (!Str::contains($v, "_to_") && ($this->input->getOption('controller') || $this->input->getOption('all'))) {
129 130 131 132
                $this->makeRepositoryInterface();
                $this->makeRepository();
                $this->makeController();
            }
133 134 135
            if (!Str::contains($v, "_to_") && ($this->input->getOption('validator') || $this->input->getOption('all'))) {
                $this->makeValidator();
            }
136 137 138
            if (!Str::contains($v, "_to_") && $this->input->getOption('seeder')) {
                $this->makeSeeder();
            }
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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
            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];
                        $relation['local_table_key'] = $fv['column_name'];
                    } else {
                        $relation['constraint_table'] = $ts[0];
                        $relation['constraint_table_key'] = Str::singular($ts[0]) . "_id";
                        $relation['local_table'] = $ts[1];
                        $relation['local_table_key'] = $fv['column_name'];
                    }
                    $relation['relation_table'] = $fv['table_name'];
204
                    $relation['function'] = Str::snake($relation['constraint_table']);
205 206 207 208 209 210 211 212
                    $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;
                    }
213
                    $relation['function'] = Str::snake(Str::singular($relation['relation_table']));
214 215 216 217 218 219 220 221 222 223
                    $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'];
224
                    $reverseRelation['function'] = Str::snake($reverseRelation['relation_table']);
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 278 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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
                    $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) {
            $v['fields'] = isset($fields[$k]) ? $fields[$k] : [];
            $v['constraints'] = isset($constraints[$k]) ? $constraints[$k] : [];
            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;
        $tables = $tables;
        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 = '';
        $casts = '';
        $timestamps = 0;
        $softDelete = false;
        $list = $info['fields'];
        foreach ($list as $k => $v) {
            $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',
                'date' => '\Carbon\Carbon',
                'datetime' => '\Carbon\Carbon',
                'custom_datetime' => '\Carbon\Carbon',
                'timestamp' => '\Carbon\Carbon',
                'collection' => 'collection',
                'array' => 'array',
                'json' => 'string',
            ];
349 350
            $properties .= " * @property " . (isset($pc[$v['data_type']]) ? $pc[$v['data_type']] : "string") . " $" . $name . ($v['column_comment'] ? " " . $v['column_comment'] : "") . "\n";
            if ($name == 'created_at' || $name == 'updated_at') {
梁俊杰's avatar
梁俊杰 committed
351
                $casts .= "\t\t'" . $name . "'=>'datetime',\n";
352 353 354
                $timestamps++;
            }
            if ($name == 'deleted_at') {
梁俊杰's avatar
梁俊杰 committed
355
                $casts .= "\t\t'" . $name . "'=>'datetime',\n";
356 357 358 359 360
                $softDelete = true;
            }
            if (in_array($name, $filterFields)) {
                continue;
            }
361
            $fillAble .= "\t\t'" . $name . "'," . "\n";
362
            if (isset($this->cc[$v['data_type']]) && $this->cc[$v['data_type']] != 'string') {
王源's avatar
王源 committed
363 364
                if ($this->cc[$v['data_type']] == 'timestamp') {
                    $casts .= "\t\t'" . $name . "'=>'datetime',\n";
王源's avatar
王源 committed
365 366
                } else if ($this->cc[$v['data_type']] == 'decimal') {
                    $casts .= "\t\t'" . $name . "'=>'float',\n";
王源's avatar
王源 committed
367 368 369
                } else {
                    $casts .= "\t\t'" . $name . "'=>'" . $this->cc[$v['data_type']] . "',\n";
                }
370 371 372 373 374 375 376
            }
        }
        $relation = '';
        if (isset($info['relations']) && $info['relations']) {
            $relation .= "\n";
            if (isset($info['relations']['belongsTo'])) {
                foreach ($info['relations']['belongsTo'] as $v) {
王源's avatar
王源 committed
377 378
                    $relation .= "\n\t/**\n\t* 属于" . $v['relation_model_name'] . "的关联\n\t*/";
                    $relation .= "\n\tpublic function " . $v['function'] . "()";
379
                    $relation .= "\n\t{";
梁俊杰's avatar
梁俊杰 committed
380
                    $relation .= "\n\t\t" . 'return $this->belongsTo(' . $v['relation_model_name'] . "::class);";
381 382 383 384 385 386 387 388 389 390 391 392
                    $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
393
                        . $v['relation_table'] . "');";
394 395 396 397 398 399 400 401 402 403 404
                    $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
405
                    $relation .= "\n\t\t" . 'return $this->hasMany(' . $v['relation_model_name'] . "::class);";
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 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 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
                    $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";
        }
        $patterns = ['%namespace%', "%ClassName%", "%fillAble%", "%casts%", '%relations%', '%timestamps%', '%properties%', '%SoftDelete%'];
        $replacements = [$sdn, $modelName, $fillAble, $casts, $relation, ($timestamps == 2 ? 'true' : 'false'), $properties, $sd];

        $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%']);
        $replacements = array_merge($replacements, [$author ? $author : "Auto generated.", date("Y-m-d"), date("h:i:s")]);
        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);

        $this->info("<info>[INFO] Created File:</info> {$file}");
        return true;
    }

王源's avatar
王源 committed
469
    private function makeRepositoryInterface()
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    {
        $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;
        //列表
498
        $list = "\$conditions = \$this->request->all();\n";
499 500 501
        $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
502
                $list .= "\t\t\tif(isset(\$conditions['" . $v['column_name'] . "']) && \$conditions['" . $v['column_name'] . "'] !== '') {\n";
503 504 505
                $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
506
                $list .= "\t\t\tif(isset(\$conditions['" . $v['column_name'] . "']) && \$conditions['keyword'] !== '') {\n";
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
                $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";
        //新增
        $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";
        //删除
        $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 = [];
                    foreach ($info['relations']['belongsTo'] as $k => $v) {
                        $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) {
565 566
                        $f = Str::camel($v['function']);
                        $rs .= "\n\tpublic function {$f}(\$id): array\n";
567
                        $rs .= "\t{\n";
王源's avatar
王源 committed
568
                        $rs .= "\t\t\$pageSize = (int)\$this->request->input('page_size', DEFAULT_PAGE_SIZE);\n";
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
                        $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);
        $table = isset($this->allTableStructures[$table]) ? $this->allTableStructures[$table] : [];
        return $table;
    }

    /**
     * 添加类到依赖注入配置文件
     * @param $modelClass
     * @return bool
     */
    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) {
                return true;
            }
            $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) {
635
                        $f = Str::camel($v['function']);
636 637 638 639 640 641
                        $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 */";
642
                        $rs .= "\n\tpublic function {$f}(\$id)\n";
643
                        $rs .= "\t{\n";
644
                        $rs .= "\t\t\$data = \$this->repository->{$f}(\$id);\n";
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 674
                        $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);
    }

    /**添加Controller到路由类
     * @param $modelClass
     * @return bool
     */
    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) {
                return true;
            }
            $info = $this->currentTableStructure;
梁俊杰's avatar
梁俊杰 committed
675
            $tableComment = (isset($info['table_comment']) && $info['table_comment']) ? $info['table_comment'] : $table;
676 677 678 679 680 681 682 683 684
            $content .= "\n\t// " . $tableComment;
            $content .= "\n\tRouter::addGroup('" . $group . "', function () {";
            $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::post('', 'App\Controller\\" . $modelClass . "Controller@create');";
            $content .= "\n\t\tRouter::patch('/{id}', 'App\Controller\\" . $modelClass . "Controller@update');";
            $content .= "\n\t\tRouter::delete('/{id}', 'App\Controller\\" . $modelClass . "Controller@delete');";
            if ($routes) {
                foreach ($routes as $v) {
王源's avatar
王源 committed
685
                    $content .= "\n\t\tRouter::get('/$v/\{id\}', 'App\Controller\\" . $modelClass . "Controller@$v');";
686 687 688 689 690 691 692
                }
            }
            $content .= "\n\t});";
            $this->writeToFile($file, $content);
        }
    }

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
    /**
     * 创建验证文件
     */
    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 = '';
        $messages = [];
        $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'];
//            $extra = $v['extra'];
            $comment = $v['column_comment'];
            $length = $v['length'];
            $msgName = ($comment ? $comment : $name);
            if (in_array($name, $filterFields)) {
                continue;
            }
            $rs = [];
            $required = "nullable";
            if ($null !== 'YES') {
王源's avatar
王源 committed
728
                if ($default !== '' && $default !== '0' && !$default) {
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
                    $required = "required";
                    $messages[] = "\t\t'{$name}.{$required}' => '{$msgName}不能为空!'";
                }
            }
            $rs[] = $required;
            switch ($type) {
                case "bigint":
                case "smallint":
                case "tinyint":
                case "mediumint":
                case "int":
                case "integer":
                    $rs[] = 'integer';
                    $messages[] = "\t\t'{$name}.integer' => '{$msgName}只能是整数!'";
                    break;
                case "decimal":
                case "double":
                case "float":
                case "numeric":
                case "real":
                    $rs[] = 'numeric';
                    $messages[] = "\t\t'{$name}.numeric' => '{$msgName}只能是数字支持小数!'";
                    break;
                case "char":
                case "varchar":
                case "tinytext":
                case "mediumtext":
                case "longtext":
                case "text":
                    $rs[] = 'string';
                    if ($length) {
                        $rs[] = 'max:' . $length;
                        $messages[] = "\t\t'{$name}.max' => '{$msgName}字符长度不能超过{$length}!'";
                    }
                    break;
                case "date":
                case "datetime":
                case "time":
                case "timestamp":
                case "year":
                    $rs[] = 'date';
                    $messages[] = "\t\t'{$name}.date' => '{$msgName}不符合日期时间格式!'";
                    break;
                case "enum":
                case "set":
                    $rs[] = 'in:[' . $length . "]";
                    $messages[] = "\t\t'{$name}.in' => '{$msgName}的值只能在[{$length}]列表中!'";
                    break;
                default:
                    if (Str::contains($name, "email") || Str::contains($name, "e-mail") || Str::contains($name, "e_mail")) {
                        $rs[] = 'email';
                        $messages[] = "\t\t'{$name}.email' => '{$msgName}只支持邮箱格式!'";
                    } elseif ($name == 'url'
                        || Str::contains($name, "_url")
                        || Str::contains($name, "url_")) {
                        $rs[] = 'url';
                        $messages[] = "\t\t'{$name}.email' => '{$msgName}只支持url格式!'";
                    } elseif ($name == 'date'
                        || Str::contains($name, "_date")
                        || Str::contains($name, "date_")) {
                        $rs[] = 'date';
                        $messages[] = "\t\t'{$name}.email' => '{$msgName}不符合日期时间格式!'";
                    }
                    break;
            }

            if ($key == 'uni') {
                $rs[] = "unique:$table," . $name;
                $messages[] = "\t\t'{$name}.unique' => '{$msgName}的值在数据库中已经存在!'";
            }
            if ($comment) {
                $attributes .= "\t\t'" . $name . "' => '" . $comment . "'," . "\n";
            }
            $rules .= "\t\t\t'" . $name . "' => '" . implode("|", $rs) . "'," . ($comment ? "// " . $comment . "-" . $type : "//" . $type) . "\n";
        }
        $messages = join(",\n", $messages);
        $patterns = ["%ModelClass%", '%createRules%', '%updateRules%', '%attributes%', '%messages%'];
        $createRules = $rules;
        $updateRules = str_replace("nullable", "sometimes|nullable", $rules);
        $updateRules = str_replace("required", "sometimes|required", $updateRules);
        $replacements = [$modelClass, $createRules, $updateRules, $attributes, $messages];
        $content = $this->buildField($patterns, $replacements, $content);
        $this->writeToFile($file, $content);
    }

814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    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");
        $generateCount = $generateCount ? $generateCount : 30;
        $otherProcess = "";
        $list = $info['fields'];
        $maxNumber = 4;
        foreach ($list as $v) {
            $name = $v['column_name'];
            $type = $v['data_type'];
            $nullAble = ($v['is_nullable'] !== 'YES');
            $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") {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->randomElement([0,1]),";
                    } else if (Str::contains($name, "status")) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->randomDigit,";
                    } 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 . ";";
                            $fields[] = "\t\t\t\t'{$name}' => $o::orderBy(Db::raw('rand()'))->first()->id,";
                        } else {
                            $n = ((isset($length[0]) && $length[0] && $length[0] < $maxNumber) ? $length[0] : $maxNumber);
                            $n = rand(1, $n);
                            $fields[] = "\t\t\t\t'{$name}' => \$faker->randomNumber($n),";
                        }
                    } else {
                        $n = ((isset($length[0]) && $length[0] < $maxNumber) ? $length[0] : $maxNumber);
                        $n = rand(1, $n);
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->randomNumber($n),";
                    }
                    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
879 880
                    $n3 = $n2 + 20;
                    $fields[] = "\t\t\t\t'{$name}' => \$faker->randomFloat($n,$n2,$n3),";
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
                    break;
                case "char":
                case "varchar":
                    $n = ((isset($length[0]) && $length[0]) ? $length[0] : 255);
                    if ($name == "ip" || $name == "ip" || $name == "ip_address" || $name == "ip_addr") {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->ipv4,";
                    } else if (Str::contains($name, "email")) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->email,";
                    } else if ($name == "userName" || $name == "user_name" || $name == "uname") {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->userName,";
                    } else if ($name == "url" || $name == "domain" || Str::endsWith($name, "_url") || Str::startsWith($name, "url_")) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->url,";
                    } else if ($name == "company" || $name == "company_name") {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->company,";
                    } else if ($name == "gender") {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->title(),";
                    } else if ($name == "name") {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->name(),";
                    } else if (Str::contains($name, "city")) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->city,";
                    } else if (Str::contains($name, "street") || Str::contains($name, "address")) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->streetAddress,";
                    } else if (Str::contains($name, "postcode")) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->postcode,";
                    } else if (Str::contains($name, "country")) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->country,";
                    } else if (Str::contains($name, "phoneNumber") || $name == "tel" || $name == "mobile" || Str::contains($name, "phone")) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->phoneNumber,";
                    } else if (Str::contains($name, "color")) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->colorName,";
                    } else if (Str::contains($name, "image") || Str::contains($name, "path")) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->imageUrl(640, 480),";
                    } else if ($name == "ean" || $name == "bar_code") {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->ean13,";
                    } else if ($n < 10) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->word,";
                    } elseif ($n < 100) {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->sentence(6),";
                    } else {
                        $n = rand(2, 5);
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->paragraph($n, true),";
                    }
                    break;
                case "tinytext":
                case "mediumtext":
                case "longtext":
                case "text":
                    $fields[] = "\t\t\t\t'{$name}' => \$faker->text,";
                    break;
                case "date":
                    $fields[] = "\t\t\t\t'{$name}' => \$faker->date('Y-m-d'),";
                    break;
                case "datetime":
                    $fields[] = "\t\t\t\t'{$name}' => \$faker->date('Y-m-d').' '.\$faker->time('H:i:s'),";
                    break;
                case "time":
                    $fields[] = "\t\t\t\t'{$name}' => \$faker->time('H:i:s'),";
                    break;
                case "timestamp":
梁俊杰's avatar
梁俊杰 committed
940 941 942 943 944
                    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'),";
                    } else {
                        $fields[] = "\t\t\t\t'{$name}' => \$faker->unixTime(),";
                    }
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 983 984 985 986
                    break;
                case "year":
                    $fields[] = "\t\t\t\t'{$name}' => \$faker->year(),";
                    break;
                case "enum":
                case "set":
                    $n = implode(",", $length);
                    $fields[] = "\t\t\t\t'{$name}' => \$faker->randomElement([$n]),";
                    break;
                default:
                    $fields[] = "\t\t\t\t'{$name}' => \$faker->word,";
                    break;
            }
        }
        $fields = join("\n", $fields);
        $otherModel = join("", $otherModel);
        //if(isset($info['']))
        $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) {
            return true;
        }
        $content = str_replace("];", "\t\t\t" . Str::studly($this->table) . "TableSeeder::class,\n\t\t];", $content);
        $this->writeToFile($file, $content);
    }

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 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 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 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    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'];
            $key = $v['column_key'];
            $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',
                        ];
                        $t .= (isset($tc[$type]) ? $tc[$type] : $type) . "('" . $name . "'";
                        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',
                        ];
                        $t .= (isset($tc[$type]) ? $tc[$type] : $type) . "('" . $name . "')";
                        break;
                    case "binary":
                    case "varbinary":
                    case "longblob":
                    case "blob":
                    case "mediumblob":
                    case "tinyblob":
                        $t .= "binary('" . $name . "')";
                        break;
                    case "enum":
                    case "set":
                        $tc = [
                            'set' => 'enum',
                        ];
                        $t .= (isset($tc[$type]) ? $tc[$type] : $type) . "('" . $name . "'";
                        $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',
                        ];
                        $t .= (isset($tc[$type]) ? $tc[$type] : $type) . "('" . $name . "'";
                        if ($length) {
                            $t .= ", " . $length;
                        }
                        $t .= ")";
                        break;
                    default:
                        $t = '';
                        break;
                }
                if ($t) {
1141 1142
                    if ($null == 'YES') {
                        $t .= "->nullable()";
1143
                    }
王源's avatar
王源 committed
1144
                    if (($default && $default !== '') || $default === '0') {
1145 1146 1147
                        if ($type !== 'timestamp') {
                            $t .= "->default('$default')";
                        }
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
                    }
                    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) {
                        $attributes[] = "\t\t\t\$table->primary(['{$fields}']);";
                    }
                } else {
                    if ($v[0]['non_unique'] === 0) {
                        $attributes[] = "\t\t\t\$table->unique(['{$fields}'], '{$k}');";
                    } else {
                        $attributes[] = "\t\t\t\$table->index(['{$fields}'], '{$k}');";
                    }
                }
            }
        }
        //外键
        if ($info['constraints']) {
            foreach ($info['constraints'] as $k => $v) {
                $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
1199
        if (isset($info['table_comment']) && $info['table_comment']) {
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
            $tableComment = 'Db::statement("alter table `' . $table . '` comment \'' . $info['table_comment'] . '\'");';
        }
        $patterns = ["%ClassName%", '%tablename%', '%attributes%', '%tableComment%'];
        $replacements = [$className, $table, $attributes, $tableComment];
        $content = $this->buildField($patterns, $replacements, $content);
        $this->writeToFile($file, $content);

    }

    /**生成迁移文件的日期格式
     * @return string
     */
王源's avatar
王源 committed
1212
    private function getDatePrefix(): string
1213 1214 1215 1216
    {
        return date('Y_m_dHis');
    }

王源's avatar
王源 committed
1217
    public function configure()
1218 1219 1220 1221 1222 1223 1224
    {
        //$this->call()
        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, '生成迁移文件');
1225
        $this->addOption('validator', 'l', InputOption::VALUE_NONE, '生成验证文件');
1226 1227
        $this->addOption('author', 'r', InputOption::VALUE_OPTIONAL, '文件作者,后面可跟空格名字,表示生成的文件作者');
        $this->addOption('seeder', 's', InputOption::VALUE_OPTIONAL, '生成数据填充文件,后面可跟空格数字,表示生成的数据量');
1228 1229 1230 1231 1232 1233 1234 1235 1236
        $this->addOption('force', 'f', InputOption::VALUE_NONE, '文件存在是否覆盖');
        $this->addOption('database', 'd', InputOption::VALUE_NONE, '全数据库索引自动生成全站文件');
        $this->setDescription('根据数据表生成model文件和迁移文件和控制器');
    }

    /**
     * 配置文件内容
     * @return array
     */
王源's avatar
王源 committed
1237
    protected function getArguments()
1238 1239 1240 1241 1242 1243
    {
        return [
            ['name', InputArgument::OPTIONAL, '数据库表名'],
        ];
    }
}