审查视图

application/admin/command/Crud.php 66.0 KB
Karson authored
1 2 3 4 5 6 7 8 9 10 11
<?php

namespace app\admin\command;

use fast\Form;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
12
use think\Exception;
13
use think\exception\ErrorException;
Karson authored
14
use think\Lang;
Karson authored
15
use think\Loader;
Karson authored
16 17 18

class Crud extends Command
{
19 20
    protected $stubList = [];
21 22 23
    protected $internalKeywords = [
        'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor'
    ];
Karson authored
24 25 26 27 28 29 30 31 32 33
    /**
     * Selectpage搜索字段关联
     */
    protected $fieldSelectpageMap = [
        'nickname' => ['user_id', 'user_ids', 'admin_id', 'admin_ids']
    ];

    /**
     * Enum类型识别为单选框的结尾字符,默认会识别为单选下拉列表
     */
34
    protected $enumRadioSuffix = ['data', 'state', 'status'];
Karson authored
35 36 37 38

    /**
     * Set类型识别为复选框的结尾字符,默认会识别为多选下拉列表
     */
39
    protected $setCheckboxSuffix = ['data', 'state', 'status'];
Karson authored
40 41

    /**
42
     * Int类型识别为日期时间的结尾字符,默认会识别为日期文本框
Karson authored
43
     */
44
    protected $intDateSuffix = ['time'];
Karson authored
45 46

    /**
Karson authored
47
     * 开关后缀
Karson authored
48
     */
49 50 51
    protected $switchSuffix = ['switch'];

    /**
52 53 54 55 56
     * 富文本后缀
     */
    protected $editorSuffix = ['content'];

    /**
Karson authored
57 58 59 60 61
     * 城市后缀
     */
    protected $citySuffix = ['city'];

    /**
62 63 64 65 66
     * JSON后缀
     */
    protected $jsonSuffix = ['json'];

    /**
67 68 69 70 71 72 73 74
     * Selectpage对应的后缀
     */
    protected $selectpageSuffix = ['_id', '_ids'];

    /**
     * Selectpage多选对应的后缀
     */
    protected $selectpagesSuffix = ['_ids'];
Karson authored
75 76 77 78 79

    /**
     * 以指定字符结尾的字段格式化函数
     */
    protected $fieldFormatterSuffix = [
80
        'status' => ['type' => ['varchar', 'enum'], 'name' => 'status'],
Karson authored
81 82 83 84 85
        'icon'   => 'icon',
        'flag'   => 'flag',
        'url'    => 'url',
        'image'  => 'image',
        'images' => 'images',
86
        'avatar' => 'image',
87
        'switch' => 'toggle',
Karson authored
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
        'time'   => ['type' => ['int', 'timestamp'], 'name' => 'datetime']
    ];

    /**
     * 识别为图片字段
     */
    protected $imageField = ['image', 'images', 'avatar', 'avatars'];

    /**
     * 识别为文件字段
     */
    protected $fileField = ['file', 'files'];

    /**
     * 保留字段
     */
104
    protected $reservedField = ['admin_id'];
Karson authored
105 106

    /**
107 108 109 110 111
     * 排除字段
     */
    protected $ignoreFields = [];

    /**
Karson authored
112 113 114 115 116
     * 排序字段
     */
    protected $sortField = 'weigh';

    /**
117 118 119 120 121 122
     * 筛选字段
     * @var string
     */
    protected $headingFilterField = 'status';

    /**
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
     * 添加时间字段
     * @var string
     */
    protected $createTimeField = 'createtime';

    /**
     * 更新时间字段
     * @var string
     */
    protected $updateTimeField = 'updatetime';

    /**
     * 软删除时间字段
     * @var string
     */
    protected $deleteTimeField = 'deletetime';

    /**
Karson authored
141 142
     * 编辑器的Class
     */
Karson authored
143
    protected $editorClass = 'editor';
Karson authored
144
145 146
    /**
     * langList的key最长字节数
147
     */
148 149
    protected $fieldMaxLen = 0;
Karson authored
150 151 152
    protected function configure()
    {
        $this
Karson authored
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
            ->setName('crud')
            ->addOption('table', 't', Option::VALUE_REQUIRED, 'table name without prefix', null)
            ->addOption('controller', 'c', Option::VALUE_OPTIONAL, 'controller name', null)
            ->addOption('model', 'm', Option::VALUE_OPTIONAL, 'model name', null)
            ->addOption('fields', 'i', Option::VALUE_OPTIONAL, 'model visible fields', null)
            ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override or force delete,without tips', null)
            ->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local model', 1)
            ->addOption('relation', 'r', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table name without prefix', null)
            ->addOption('relationmodel', 'e', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation model name', null)
            ->addOption('relationforeignkey', 'k', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation foreign key', null)
            ->addOption('relationprimarykey', 'p', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation primary key', null)
            ->addOption('relationfields', 's', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table fields', null)
            ->addOption('relationmode', 'o', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table mode,hasone or belongsto', null)
            ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete all files generated by CRUD', null)
            ->addOption('menu', 'u', Option::VALUE_OPTIONAL, 'create menu when CRUD completed', null)
            ->addOption('setcheckboxsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate checkbox component with suffix', null)
            ->addOption('enumradiosuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate radio component with suffix', null)
            ->addOption('imagefield', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate image component with suffix', null)
            ->addOption('filefield', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate file component with suffix', null)
            ->addOption('intdatesuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate date component with suffix', null)
            ->addOption('switchsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate switch component with suffix', null)
            ->addOption('citysuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate citypicker component with suffix', null)
175
            ->addOption('jsonsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate fieldlist component with suffix', null)
Karson authored
176 177 178 179
            ->addOption('selectpagesuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate selectpage component with suffix', null)
            ->addOption('selectpagessuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate multiple selectpage component with suffix', null)
            ->addOption('ignorefields', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'ignore fields', null)
            ->addOption('sortfield', null, Option::VALUE_OPTIONAL, 'sort field', null)
180
            ->addOption('headingfilterfield', null, Option::VALUE_OPTIONAL, 'heading filter field', null)
Karson authored
181
            ->addOption('editorclass', null, Option::VALUE_OPTIONAL, 'automatically generate editor class', null)
182
            ->addOption('db', null, Option::VALUE_OPTIONAL, 'database config name', 'database')
Karson authored
183
            ->setDescription('Build CRUD controller and model from table');
Karson authored
184 185 186 187 188
    }

    protected function execute(Input $input, Output $output)
    {
        $adminPath = dirname(__DIR__) . DS;
189 190
        //数据库
        $db = $input->getOption('db');
Karson authored
191
        //表名
192
        $table = $input->getOption('table') ?: '';
Karson authored
193 194 195 196
        //自定义控制器
        $controller = $input->getOption('controller');
        //自定义模型
        $model = $input->getOption('model');
197
        $model = $model ? $model : $controller;
198 199
        //验证器类
        $validate = $model;
Karson authored
200 201
        //自定义显示字段
        $fields = $input->getOption('fields');
Karson authored
202 203 204 205
        //强制覆盖
        $force = $input->getOption('force');
        //是否为本地model,为0时表示为全局model将会把model放在app/common/model中
        $local = $input->getOption('local');
Karson authored
206
        if (!$table) {
207
            throw new Exception('table name can\'t empty');
Karson authored
208
        }
Karson authored
209 210
        //是否生成菜单
        $menu = $input->getOption("menu");
211 212 213 214 215
        //关联表
        $relation = $input->getOption('relation');
        //自定义关联表模型
        $relationModel = $input->getOption('relationmodel');
        //模式
Karson authored
216
        $relationMode = $mode = $input->getOption('relationmode');
217 218 219 220
        //外键
        $relationForeignKey = $input->getOption('relationforeignkey');
        //主键
        $relationPrimaryKey = $input->getOption('relationprimarykey');
Karson authored
221 222
        //关联表显示字段
        $relationFields = $input->getOption('relationfields');
223 224 225 226 227 228 229 230 231 232 233 234
        //复选框后缀
        $setcheckboxsuffix = $input->getOption('setcheckboxsuffix');
        //单选框后缀
        $enumradiosuffix = $input->getOption('enumradiosuffix');
        //图片后缀
        $imagefield = $input->getOption('imagefield');
        //文件后缀
        $filefield = $input->getOption('filefield');
        //日期后缀
        $intdatesuffix = $input->getOption('intdatesuffix');
        //开关后缀
        $switchsuffix = $input->getOption('switchsuffix');
Karson authored
235 236
        //城市后缀
        $citysuffix = $input->getOption('citysuffix');
237 238
        //JSON配置后缀
        $jsonsuffix = $input->getOption('jsonsuffix');
239 240 241 242
        //selectpage后缀
        $selectpagesuffix = $input->getOption('selectpagesuffix');
        //selectpage多选后缀
        $selectpagessuffix = $input->getOption('selectpagessuffix');
243 244
        //排除字段
        $ignoreFields = $input->getOption('ignorefields');
245 246
        //排序字段
        $sortfield = $input->getOption('sortfield');
247 248
        //顶部筛选过滤字段
        $headingfilterfield = $input->getOption('headingfilterfield');
249 250
        //编辑器Class
        $editorclass = $input->getOption('editorclass');
251
        if ($setcheckboxsuffix) {
252
            $this->setCheckboxSuffix = $setcheckboxsuffix;
253 254
        }
        if ($enumradiosuffix) {
255
            $this->enumRadioSuffix = $enumradiosuffix;
256 257
        }
        if ($imagefield) {
258
            $this->imageField = $imagefield;
259 260
        }
        if ($filefield) {
261
            $this->fileField = $filefield;
262 263
        }
        if ($intdatesuffix) {
264
            $this->intDateSuffix = $intdatesuffix;
265 266
        }
        if ($switchsuffix) {
267
            $this->switchSuffix = $switchsuffix;
268 269
        }
        if ($citysuffix) {
Karson authored
270
            $this->citySuffix = $citysuffix;
271
        }
272 273 274
        if ($jsonsuffix) {
            $this->jsonSuffix = $jsonsuffix;
        }
275
        if ($selectpagesuffix) {
276
            $this->selectpageSuffix = $selectpagesuffix;
277 278
        }
        if ($selectpagessuffix) {
279
            $this->selectpagesSuffix = $selectpagessuffix;
280 281
        }
        if ($ignoreFields) {
282
            $this->ignoreFields = $ignoreFields;
283 284
        }
        if ($editorclass) {
285
            $this->editorClass = $editorclass;
286 287
        }
        if ($sortfield) {
288
            $this->sortField = $sortfield;
289 290
        }
        if ($headingfilterfield) {
291
            $this->headingFilterField = $headingfilterfield;
292 293 294
        }

        $this->reservedField = array_merge($this->reservedField, [$this->createTimeField, $this->updateTimeField, $this->deleteTimeField]);
295
296 297 298
        $dbconnect = Db::connect($db);
        $dbname = Config::get($db . '.database');
        $prefix = Config::get($db . '.prefix');
299
300 301 302 303 304
        //模块
        $moduleName = 'admin';
        $modelModuleName = $local ? $moduleName : 'common';
        $validateModuleName = $local ? $moduleName : 'common';
305
        //检查主表
Karson authored
306
        $modelName = $table = stripos($table, $prefix) === 0 ? substr($table, strlen($prefix)) : $table;
307
        $modelTableType = 'table';
Karson authored
308
        $modelTableTypeName = $modelTableName = $modelName;
309
        $modelTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true);
Karson authored
310
        if (!$modelTableInfo) {
311
            $modelTableType = 'name';
Karson authored
312
            $modelTableName = $prefix . $modelName;
313
            $modelTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true);
Karson authored
314
            if (!$modelTableInfo) {
315 316
                throw new Exception("table not found");
            }
Karson authored
317
        }
Karson authored
318
        $modelTableInfo = $modelTableInfo[0];
319
Karson authored
320
        $relations = [];
321
        //检查关联表
Karson authored
322 323 324 325 326 327 328 329
        if ($relation) {
            $relationArr = $relation;
            $relations = [];

            foreach ($relationArr as $index => $relationTable) {
                $relationName = stripos($relationTable, $prefix) === 0 ? substr($relationTable, strlen($prefix)) : $relationTable;
                $relationTableType = 'table';
                $relationTableTypeName = $relationTableName = $relationName;
330
                $relationTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], true);
Karson authored
331 332 333
                if (!$relationTableInfo) {
                    $relationTableType = 'name';
                    $relationTableName = $prefix . $relationName;
334
                    $relationTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], true);
Karson authored
335 336 337
                    if (!$relationTableInfo) {
                        throw new Exception("relation table not found");
                    }
338
                }
Karson authored
339 340 341
                $relationTableInfo = $relationTableInfo[0];
                $relationModel = isset($relationModel[$index]) ? $relationModel[$index] : '';
342
                list($relationNamespace, $relationName, $relationFile) = $this->getModelData($modelModuleName, $relationModel, $relationName);
Karson authored
343 344 345 346

                $relations[] = [
                    //关联表基础名
                    'relationName'          => $relationName,
347 348
                    //关联表类命名空间
                    'relationNamespace'     => $relationNamespace,
Karson authored
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
                    //关联模型名
                    'relationModel'         => $relationModel,
                    //关联文件
                    'relationFile'          => $relationFile,
                    //关联表名称
                    'relationTableName'     => $relationTableName,
                    //关联表信息
                    'relationTableInfo'     => $relationTableInfo,
                    //关联模型表类型(name或table)
                    'relationTableType'     => $relationTableType,
                    //关联模型表类型名称
                    'relationTableTypeName' => $relationTableTypeName,
                    //关联模式
                    'relationFields'        => isset($relationFields[$index]) ? explode(',', $relationFields[$index]) : [],
                    //关联模式
                    'relationMode'          => isset($relationMode[$index]) ? $relationMode[$index] : 'belongsto',
                    //关联表外键
                    'relationForeignKey'    => isset($relationForeignKey[$index]) ? $relationForeignKey[$index] : Loader::parseName($relationName) . '_id',
                    //关联表主键
                    'relationPrimaryKey'    => isset($relationPrimaryKey[$index]) ? $relationPrimaryKey[$index] : '',
                ];
370 371 372
            }
        }
Karson authored
373
        //根据表名匹配对应的Fontawesome图标
374
        $iconPath = ROOT_PATH . str_replace('/', DS, '/public/assets/libs/font-awesome/less/variables.less');
375
        $iconName = is_file($iconPath) && stripos(file_get_contents($iconPath), '@fa-var-' . $table . ':') ? 'fa fa-' . $table : 'fa fa-circle-o';
Karson authored
376
377 378 379 380 381 382 383
        //控制器
        list($controllerNamespace, $controllerName, $controllerFile, $controllerArr) = $this->getControllerData($moduleName, $controller, $table);
        //模型
        list($modelNamespace, $modelName, $modelFile, $modelArr) = $this->getModelData($modelModuleName, $model, $table);
        //验证器
        list($validateNamespace, $validateName, $validateFile, $validateArr) = $this->getValidateData($validateModuleName, $validate, $table);
384 385
        //处理基础文件名,取消所有下划线并转换为小写
        $baseNameArr = $controllerArr;
386
        $baseFileName = Loader::parseName(array_pop($baseNameArr), 0);
387 388
        array_push($baseNameArr, $baseFileName);
        $controllerBaseName = strtolower(implode(DS, $baseNameArr));
389
        $controllerUrl = strtolower(implode('/', $baseNameArr));
390 391

        //视图文件
392
        $viewArr = $controllerArr;
393 394
        $lastValue = array_pop($viewArr);
        $viewArr[] = Loader::parseName($lastValue, 0);
395
        array_unshift($viewArr, 'view');
396
        $viewDir = $adminPath . strtolower(implode(DS, $viewArr)) . DS;
Karson authored
397
398
        //最终将生成的文件路径
399
        $javascriptFile = ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend' . DS . $controllerBaseName . '.js';
400 401 402
        $addFile = $viewDir . 'add.html';
        $editFile = $viewDir . 'edit.html';
        $indexFile = $viewDir . 'index.html';
403
        $recyclebinFile = $viewDir . 'recyclebin.html';
404
        $langFile = $adminPath . 'lang' . DS . Lang::detect() . DS . $controllerBaseName . '.php';
405 406 407

        //是否为删除模式
        $delete = $input->getOption('delete');
Karson authored
408
        if ($delete) {
409
            $readyFiles = [$controllerFile, $modelFile, $validateFile, $addFile, $editFile, $indexFile, $recyclebinFile, $langFile, $javascriptFile];
Karson authored
410
            foreach ($readyFiles as $k => $v) {
411 412
                $output->warning($v);
            }
Karson authored
413 414 415 416 417 418
            if (!$force) {
                $output->info("Are you sure you want to delete all those files?  Type 'yes' to continue: ");
                $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
                if (trim($line) != 'yes') {
                    throw new Exception("Operation is aborted!");
                }
419
            }
Karson authored
420
            foreach ($readyFiles as $k => $v) {
421
                if (file_exists($v)) {
Karson authored
422
                    unlink($v);
423
                }
424
                //删除空文件夹
425 426 427 428 429 430 431 432 433 434
                switch ($v) {
                    case $modelFile:
                        $this->removeEmptyBaseDir($v, $modelArr);
                        break;
                    case $validateFile:
                        $this->removeEmptyBaseDir($v, $validateArr);
                        break;
                    case $addFile:
                    case $editFile:
                    case $indexFile:
435
                    case $recyclebinFile:
436 437 438 439
                        $this->removeEmptyBaseDir($v, $viewArr);
                        break;
                    default:
                        $this->removeEmptyBaseDir($v, $controllerArr);
440
                }
441 442
            }
443 444 445 446 447
            //继续删除菜单
            if ($menu) {
                exec("php think menu -c {$controllerUrl} -d 1 -f 1");
            }
448 449 450 451 452
            $output->info("Delete Successed");
            return;
        }

        //非覆盖模式时如果存在控制器文件则报错
Karson authored
453
        if (is_file($controllerFile) && !$force) {
454 455 456
            throw new Exception("controller already exists!\nIf you need to rebuild again, use the parameter --force=true ");
        }
Karson authored
457
        //非覆盖模式时如果存在模型文件则报错
Karson authored
458
        if (is_file($modelFile) && !$force) {
459 460 461 462
            throw new Exception("model already exists!\nIf you need to rebuild again, use the parameter --force=true ");
        }

        //非覆盖模式时如果存在验证文件则报错
Karson authored
463
        if (is_file($validateFile) && !$force) {
464
            throw new Exception("validate already exists!\nIf you need to rebuild again, use the parameter --force=true ");
Karson authored
465 466
        }
467 468
        require $adminPath . 'common.php';
Karson authored
469
        //从数据库中获取表字段信息
470
        $sql = "SELECT * FROM `information_schema`.`columns` "
Karson authored
471 472 473
            . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
            . "ORDER BY ORDINAL_POSITION";
        //加载主表的列
474
        $columnList = $dbconnect->query($sql, [$dbname, $modelTableName]);
475
        $fieldArr = [];
Karson authored
476
        foreach ($columnList as $k => $v) {
477 478 479
            $fieldArr[] = $v['COLUMN_NAME'];
        }
Karson authored
480 481
        // 加载关联表的列
        foreach ($relations as $index => &$relation) {
482
            $relationColumnList = $dbconnect->query($sql, [$dbname, $relation['relationTableName']]);
Karson authored
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

            $relationFieldList = [];
            foreach ($relationColumnList as $k => $v) {
                $relationFieldList[] = $v['COLUMN_NAME'];
            }
            if (!$relation['relationPrimaryKey']) {
                foreach ($relationColumnList as $k => $v) {
                    if ($v['COLUMN_KEY'] == 'PRI') {
                        $relation['relationPrimaryKey'] = $v['COLUMN_NAME'];
                        break;
                    }
                }
            }
            // 如果主键为空
            if (!$relation['relationPrimaryKey']) {
                throw new Exception('Relation Primary key not found!');
            }
            // 如果主键不在表字段中
            if (!in_array($relation['relationPrimaryKey'], $relationFieldList)) {
                throw new Exception('Relation Primary key not found in table!');
            }
            $relation['relationColumnList'] = $relationColumnList;
            $relation['relationFieldList'] = $relationFieldList;
Karson authored
506
        }
Karson authored
507
        unset($relation);
Karson authored
508 509 510 511 512 513 514

        $addList = [];
        $editList = [];
        $javascriptList = [];
        $langList = [];
        $field = 'id';
        $order = 'id';
515
        $priDefined = false;
516
        $priKey = '';
Karson authored
517 518 519
        $relationPrimaryKey = '';
        foreach ($columnList as $k => $v) {
            if ($v['COLUMN_KEY'] == 'PRI') {
520
                $priKey = $v['COLUMN_NAME'];
521 522 523
                break;
            }
        }
Karson authored
524
        if (!$priKey) {
525 526
            throw new Exception('Primary key not found!');
        }
527
Karson authored
528
        $order = $priKey;
529 530

        //如果是关联模型
Karson authored
531 532 533 534 535 536 537
        foreach ($relations as $index => &$relation) {
            if ($relation['relationMode'] == 'hasone') {
                $relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : $table . "_id";
                $relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;

                if (!in_array($relationForeignKey, $relation['relationFieldList'])) {
                    throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationForeignKey . ']');
538
                }
Karson authored
539 540
                if (!in_array($relationPrimaryKey, $fieldArr)) {
                    throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationPrimaryKey . ']');
541
                }
Karson authored
542 543 544 545 546
            } else {
                $relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : Loader::parseName($relation['relationName']) . "_id";
                $relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $relation['relationPriKey'];
                if (!in_array($relationForeignKey, $fieldArr)) {
                    throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationForeignKey . ']');
547
                }
Karson authored
548 549
                if (!in_array($relationPrimaryKey, $relation['relationFieldList'])) {
                    throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationPrimaryKey . ']');
550 551
                }
            }
Karson authored
552 553
            $relation['relationForeignKey'] = $relationForeignKey;
            $relation['relationPrimaryKey'] = $relationPrimaryKey;
554
            $relation['relationClassName'] = $modelNamespace != $relation['relationNamespace'] ? $relation['relationNamespace'] . '\\' . $relation['relationName'] : $relation['relationName'];
555
        }
Karson authored
556
        unset($relation);
Karson authored
557
Karson authored
558
        try {
559
            Form::setEscapeHtml(false);
Karson authored
560 561
            $setAttrArr = [];
            $getAttrArr = [];
562
            $getEnumArr = [];
Karson authored
563
            $appendAttrList = [];
564
            $controllerAssignList = [];
565
            $headingHtml = '{:build_heading()}';
566
            $recyclebinHtml = '';
567 568

            //循环所有字段,开始构造视图的HTML和JS信息
Karson authored
569
            foreach ($columnList as $k => $v) {
570 571 572
                $field = $v['COLUMN_NAME'];
                $itemArr = [];
                // 这里构建Enum和Set类型的列表数据
Karson authored
573
                if (in_array($v['DATA_TYPE'], ['enum', 'set', 'tinyint'])) {
574 575 576 577
                    if ($v['DATA_TYPE'] !== 'tinyint') {
                        $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
                        $itemArr = explode(',', str_replace("'", '', $itemArr));
                    }
578
                    $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
Karson authored
579 580 581 582
                    //如果类型为tinyint且有使用备注数据
                    if ($itemArr && $v['DATA_TYPE'] == 'tinyint') {
                        $v['DATA_TYPE'] = 'enum';
                    }
Karson authored
583
                }
584
                // 语言列表
Karson authored
585
                if ($v['COLUMN_COMMENT'] != '') {
586
                    $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
Karson authored
587
                }
588
                $inputType = '';
589
                //保留字段不能修改和添加
Karson authored
590
                if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $this->reservedField) && !in_array($field, $this->ignoreFields)) {
591 592 593 594 595 596 597 598 599
                    $inputType = $this->getFieldType($v);

                    // 如果是number类型时增加一个步长
                    $step = $inputType == 'number' && $v['NUMERIC_SCALE'] > 0 ? "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1" : 0;

                    $attrArr = ['id' => "c-{$field}"];
                    $cssClassArr = ['form-control'];
                    $fieldName = "row[{$field}]";
                    $defaultValue = $v['COLUMN_DEFAULT'];
600
                    $editValue = "{\$row.{$field}|htmlentities}";
601
                    // 如果默认值非null,则是一个必选项
Karson authored
602
                    if ($v['IS_NULLABLE'] == 'NO') {
Karson authored
603
                        $attrArr['data-rule'] = 'required';
Karson authored
604
                    }
605
Karson authored
606
                    if ($inputType == 'select') {
607 608
                        $cssClassArr[] = 'selectpicker';
                        $attrArr['class'] = implode(' ', $cssClassArr);
Karson authored
609
                        if ($v['DATA_TYPE'] == 'set') {
610
                            $attrArr['multiple'] = '';
611
                            $fieldName .= "[]";
612
                        }
613 614 615
                        $attrArr['name'] = $fieldName;

                        $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
Karson authored
616
617
                        $itemArr = $this->getLangArray($itemArr, false);
Karson authored
618
                        //添加一个获取器
619
                        $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
Karson authored
620
                        if ($v['DATA_TYPE'] == 'set') {
Karson authored
621 622
                            $this->setAttr($setAttrArr, $field, $inputType);
                        }
Karson authored
623
                        $this->appendAttr($appendAttrList, $field);
624 625
                        $formAddElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
                        $formEditElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
626
                    } elseif ($inputType == 'datetime') {
627 628 629 630 631
                        $cssClassArr[] = 'datetimepicker';
                        $attrArr['class'] = implode(' ', $cssClassArr);
                        $format = "YYYY-MM-DD HH:mm:ss";
                        $phpFormat = "Y-m-d H:i:s";
                        $fieldFunc = '';
Karson authored
632
                        switch ($v['DATA_TYPE']) {
633
                            case 'year':
634 635 636
                                $format = "YYYY";
                                $phpFormat = 'Y';
                                break;
637
                            case 'date':
638 639 640
                                $format = "YYYY-MM-DD";
                                $phpFormat = 'Y-m-d';
                                break;
641
                            case 'time':
642 643 644
                                $format = "HH:mm:ss";
                                $phpFormat = 'H:i:s';
                                break;
645
                            case 'timestamp':
646
                                $fieldFunc = 'datetime';
647 648
                            // no break
                            case 'datetime':
649 650 651 652 653
                                $format = "YYYY-MM-DD HH:mm:ss";
                                $phpFormat = 'Y-m-d H:i:s';
                                break;
                            default:
                                $fieldFunc = 'datetime';
654 655
                                $this->getAttr($getAttrArr, $field, $inputType);
                                $this->setAttr($setAttrArr, $field, $inputType);
Karson authored
656
                                $this->appendAttr($appendAttrList, $field);
657 658 659 660 661 662
                                break;
                        }
                        $defaultDateTime = "{:date('{$phpFormat}')}";
                        $attrArr['data-date-format'] = $format;
                        $attrArr['data-use-current'] = "true";
                        $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
663
                        $formEditElement = Form::text($fieldName, ($fieldFunc ? "{:\$row.{$field}?{$fieldFunc}(\$row.{$field}):''}" : "{\$row.{$field}{$fieldFunc}}"), $attrArr);
664
                    } elseif ($inputType == 'checkbox' || $inputType == 'radio') {
665
                        unset($attrArr['data-rule']);
666 667
                        $fieldName = $inputType == 'checkbox' ? $fieldName .= "[]" : $fieldName;
                        $attrArr['name'] = "row[{$fieldName}]";
668
669
                        $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $inputType);
670
                        $itemArr = $this->getLangArray($itemArr, false);
Karson authored
671
                        //添加一个获取器
672
                        $this->getAttr($getAttrArr, $field, $inputType);
Karson authored
673
                        if ($inputType == 'checkbox') {
Karson authored
674 675
                            $this->setAttr($setAttrArr, $field, $inputType);
                        }
Karson authored
676
                        $this->appendAttr($appendAttrList, $field);
677 678 679 680
                        $defaultValue = $inputType == 'radio' && !$defaultValue ? key($itemArr) : $defaultValue;

                        $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
                        $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
681
                    } elseif ($inputType == 'textarea') {
682
                        $cssClassArr[] = $this->isMatchSuffix($field, $this->editorSuffix) ? $this->editorClass : '';
683 684 685 686
                        $attrArr['class'] = implode(' ', $cssClassArr);
                        $attrArr['rows'] = 5;
                        $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr);
                        $formEditElement = Form::textarea($fieldName, $editValue, $attrArr);
687
                    } elseif ($inputType == 'switch') {
688
                        unset($attrArr['data-rule']);
Karson authored
689
                        if ($defaultValue === '1' || $defaultValue === 'Y') {
Karson authored
690 691
                            $yes = $defaultValue;
                            $no = $defaultValue === '1' ? '0' : 'N';
Karson authored
692
                        } else {
Karson authored
693 694
                            $no = $defaultValue;
                            $yes = $defaultValue === '0' ? '1' : 'Y';
695
                        }
696 697 698
                        if (!$itemArr) {
                            $itemArr = [$yes => 'Yes', $no => 'No'];
                        }
699 700 701
                        $stateNoClass = 'fa-flip-horizontal text-gray';
                        $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldYes' => $yes, 'fieldNo' => $no, 'attrStr' => Form::attributes($attrArr), 'fieldValue' => $defaultValue, 'fieldSwitchClass' => $defaultValue == $no ? $stateNoClass : '']);
                        $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldYes' => $yes, 'fieldNo' => $no, 'attrStr' => Form::attributes($attrArr), 'fieldValue' => "{\$row.{$field}}", 'fieldSwitchClass' => "{eq name=\"\$row.{$field}\" value=\"{$no}\"}fa-flip-horizontal text-gray{/eq}"]);
702
                    } elseif ($inputType == 'citypicker') {
Karson authored
703 704 705 706
                        $attrArr['class'] = implode(' ', $cssClassArr);
                        $attrArr['data-toggle'] = "city-picker";
                        $formAddElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $defaultValue, $attrArr));
                        $formEditElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $editValue, $attrArr));
707 708 709 710 711 712
                    } elseif ($inputType == 'fieldlist') {
                        $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
                        $itemKey = isset($itemArr['key']) ? ucfirst($itemArr['key']) : 'Key';
                        $itemValue = isset($itemArr['value']) ? ucfirst($itemArr['value']) : 'Value';
                        $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'itemKey' => $itemKey, 'itemValue' => $itemValue, 'fieldValue' => $defaultValue]);
                        $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'itemKey' => $itemKey, 'itemValue' => $itemValue, 'fieldValue' => $editValue]);
Karson authored
713
                    } else {
Karson authored
714 715
                        $search = $replace = '';
                        //特殊字段为关联搜索
Karson authored
716
                        if ($this->isMatchSuffix($field, $this->selectpageSuffix)) {
Karson authored
717 718 719 720
                            $inputType = 'text';
                            $defaultValue = '';
                            $attrArr['data-rule'] = 'required';
                            $cssClassArr[] = 'selectpage';
721 722
                            $selectpageController = str_replace('_', '/', substr($field, 0, strripos($field, '_')));
                            $attrArr['data-source'] = $selectpageController . "/index";
723
                            //如果是类型表需要特殊处理下
Karson authored
724
                            if ($selectpageController == 'category') {
725
                                $attrArr['data-source'] = 'category/selectpage';
Karson authored
726 727 728
                                $attrArr['data-params'] = '##replacetext##';
                                $search = '"##replacetext##"';
                                $replace = '\'{"custom[type]":"' . $table . '"}\'';
729 730 731 732
                            } elseif ($selectpageController == 'admin') {
                                $attrArr['data-source'] = 'auth/admin/selectpage';
                            } elseif ($selectpageController == 'user') {
                                $attrArr['data-source'] = 'user/user/index';
Karson authored
733
                            }
Karson authored
734
                            if ($this->isMatchSuffix($field, $this->selectpagesSuffix)) {
Karson authored
735 736
                                $attrArr['data-multiple'] = 'true';
                            }
Karson authored
737 738
                            foreach ($this->fieldSelectpageMap as $m => $n) {
                                if (in_array($field, $n)) {
Karson authored
739 740 741 742 743
                                    $attrArr['data-field'] = $m;
                                    break;
                                }
                            }
                        }
744
                        //因为有自动完成可输入其它内容
Karson authored
745
                        $step = array_intersect($cssClassArr, ['selectpage']) ? 0 : $step;
746
                        $attrArr['class'] = implode(' ', $cssClassArr);
Karson authored
747
                        $isUpload = false;
Karson authored
748
                        if ($this->isMatchSuffix($field, array_merge($this->imageField, $this->fileField))) {
749
                            $isUpload = true;
Karson authored
750
                        }
751
                        //如果是步长则加上步长
Karson authored
752
                        if ($step) {
753 754 755
                            $attrArr['step'] = $step;
                        }
                        //如果是图片加上个size
Karson authored
756
                        if ($isUpload) {
757 758 759 760 761
                            $attrArr['size'] = 50;
                        }

                        $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
                        $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
Karson authored
762
                        if ($search && $replace) {
Karson authored
763 764 765
                            $formAddElement = str_replace($search, $replace, $formAddElement);
                            $formEditElement = str_replace($search, $replace, $formEditElement);
                        }
766
                        //如果是图片或文件
Karson authored
767
                        if ($isUpload) {
768 769 770
                            $formAddElement = $this->getImageUpload($field, $formAddElement);
                            $formEditElement = $this->getImageUpload($field, $formEditElement);
                        }
Karson authored
771
                    }
772 773 774
                    //构造添加和编辑HTML信息
                    $addList[] = $this->getFormGroup($field, $formAddElement);
                    $editList[] = $this->getFormGroup($field, $formEditElement);
Karson authored
775 776
                }
777
                //过滤text类型字段
778
                if ($v['DATA_TYPE'] != 'text' && $inputType != 'fieldlist') {
779
                    //主键
Karson authored
780
                    if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined) {
781
                        $priDefined = true;
782
                        $javascriptList[] = "{checkbox: true}";
783
                    }
784 785 786 787
                    if ($this->deleteTimeField == $field) {
                        $recyclebinHtml = $this->getReplacedStub('html/recyclebin-html', ['controllerUrl' => $controllerUrl]);
                        continue;
                    }
788 789 790 791
                    if (!$fields || in_array($field, explode(',', $fields))) {
                        //构造JS列信息
                        $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr);
                    }
792
                    if ($this->headingFilterField && $this->headingFilterField == $field && $itemArr) {
793
                        $headingHtml = $this->getReplacedStub('html/heading-html', ['field' => $field, 'fieldName' => Loader::parseName($field, 1, false)]);
794
                    }
Karson authored
795 796
                    //排序方式,如果有指定排序字段,否则按主键排序
                    $order = $field == $this->sortField ? $this->sortField : $order;
Karson authored
797
                }
798
            }
799
Karson authored
800 801 802 803 804 805 806
            //循环关联表,追加语言包和JS列
            foreach ($relations as $index => $relation) {
                foreach ($relation['relationColumnList'] as $k => $v) {
                    // 不显示的字段直接过滤掉
                    if ($relation['relationFields'] && !in_array($v['COLUMN_NAME'], $relation['relationFields'])) {
                        continue;
                    }
807
Karson authored
808 809 810 811 812
                    $relationField = strtolower($relation['relationName']) . "." . $v['COLUMN_NAME'];
                    // 语言列表
                    if ($v['COLUMN_COMMENT'] != '') {
                        $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
                    }
813
Karson authored
814 815 816 817 818
                    //过滤text类型字段
                    if ($v['DATA_TYPE'] != 'text') {
                        //构造JS列信息
                        $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']);
                    }
819 820 821
                }
            }
822
            //JS最后一列加上操作列
823
            $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
824 825 826 827
            $addList = implode("\n", array_filter($addList));
            $editList = implode("\n", array_filter($editList));
            $javascriptList = implode(",\n", array_filter($javascriptList));
            $langList = implode(",\n", array_filter($langList));
828 829 830 831 832 833 834 835
            //数组等号对齐
            $langList = array_filter(explode(",\n", $langList . ",\n"));
            foreach ($langList as &$line) {
                if (preg_match("/^\s+'([^']+)'\s*=>\s*'([^']+)'\s*/is", $line, $matches)) {
                    $line = "    '{$matches[1]}'" . str_pad('=>', ($this->fieldMaxLen - strlen($matches[1]) + 3), ' ', STR_PAD_LEFT) . " '{$matches[2]}'";
                }
            }
            unset($line);
836
            $langList = implode(",\n", array_filter($langList));
837 838

            //表注释
Karson authored
839
            $tableComment = $modelTableInfo['Comment'];
840 841
            $tableComment = mb_substr($tableComment, -1) == '' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
842
            $modelInit = '';
Karson authored
843
            if ($priKey != $order) {
844 845 846
                $modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]);
            }
847
            $data = [
848
                'modelConnection'         => $db == 'database' ? '' : "protected \$connection = '{$db}';",
849 850
                'controllerNamespace'     => $controllerNamespace,
                'modelNamespace'          => $modelNamespace,
851
                'validateNamespace'       => $validateNamespace,
852 853
                'controllerUrl'           => $controllerUrl,
                'controllerName'          => $controllerName,
854
                'controllerAssignList'    => implode("\n", $controllerAssignList),
855
                'modelName'               => $modelName,
Karson authored
856 857 858
                'modelTableName'          => $modelTableName,
                'modelTableType'          => $modelTableType,
                'modelTableTypeName'      => $modelTableTypeName,
859
                'validateName'            => $validateName,
860 861
                'tableComment'            => $tableComment,
                'iconName'                => $iconName,
862
                'pk'                      => $priKey,
863 864
                'order'                   => $order,
                'table'                   => $table,
Karson authored
865
                'tableName'               => $modelTableName,
866 867 868 869
                'addList'                 => $addList,
                'editList'                => $editList,
                'javascriptList'          => $javascriptList,
                'langList'                => $langList,
870 871 872 873 874 875
                'sofeDeleteClassPath'     => in_array($this->deleteTimeField, $fieldArr) ? "use traits\model\SoftDelete;" : '',
                'softDelete'              => in_array($this->deleteTimeField, $fieldArr) ? "use SoftDelete;" : '',
                'modelAutoWriteTimestamp' => in_array($this->createTimeField, $fieldArr) || in_array($this->updateTimeField, $fieldArr) ? "'int'" : 'false',
                'createTime'              => in_array($this->createTimeField, $fieldArr) ? "'{$this->createTimeField}'" : 'false',
                'updateTime'              => in_array($this->updateTimeField, $fieldArr) ? "'{$this->updateTimeField}'" : 'false',
                'deleteTime'              => in_array($this->deleteTimeField, $fieldArr) ? "'{$this->deleteTimeField}'" : 'false',
Karson authored
876 877 878
                'relationSearch'          => $relations ? 'true' : 'false',
                'relationWithList'        => '',
                'relationMethodList'      => '',
879
                'controllerIndex'         => '',
880
                'recyclebinJs'            => '',
881
                'headingHtml'             => $headingHtml,
882
                'recyclebinHtml'          => $recyclebinHtml,
Karson authored
883
                'visibleFieldList'        => $fields ? "\$row->visible(['" . implode("','", array_filter(explode(',', $fields))) . "']);" : '',
Karson authored
884
                'appendAttrList'          => implode(",\n", $appendAttrList),
885
                'getEnumList'             => implode("\n\n", $getEnumArr),
Karson authored
886 887
                'getAttrList'             => implode("\n\n", $getAttrArr),
                'setAttrList'             => implode("\n\n", $setAttrArr),
888
                'modelInit'               => $modelInit,
889 890
            ];
891
            //如果使用关联模型
Karson authored
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
            if ($relations) {
                $relationWithList = $relationMethodList = $relationVisibleFieldList = [];
                foreach ($relations as $index => $relation) {
                    //需要构造关联的方法
                    $relation['relationMethod'] = strtolower($relation['relationName']);

                    //关联的模式
                    $relation['relationMode'] = $relation['relationMode'] == 'hasone' ? 'hasOne' : 'belongsTo';

                    //关联字段
                    $relation['relationPrimaryKey'] = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;

                    //预载入的方法
                    $relationWithList[] = $relation['relationMethod'];

                    unset($relation['relationColumnList'], $relation['relationFieldList'], $relation['relationTableInfo']);

                    //构造关联模型的方法
                    $relationMethodList[] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod', $relation);
912 913 914 915 916
                    //如果设置了显示主表字段,则必须显式将关联表字段显示
                    if ($fields) {
                        $relationVisibleFieldList[] = "\$row->visible(['{$relation['relationMethod']}']);";
                    }
Karson authored
917 918 919 920 921 922 923 924 925 926 927 928
                    //显示的字段
                    if ($relation['relationFields']) {
                        $relationVisibleFieldList[] = "\$row->getRelation('" . $relation['relationMethod'] . "')->visible(['" . implode("','", $relation['relationFields']) . "']);";
                    }
                }

                $data['relationWithList'] = "->with(['" . implode("','", $relationWithList) . "'])";
                $data['relationMethodList'] = implode("\n\n", $relationMethodList);
                $data['relationVisibleFieldList'] = implode("\n\t\t\t\t", $relationVisibleFieldList);

                //需要重写index方法
                $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
929
            } elseif ($fields) {
Karson authored
930
                $data = array_merge($data, ['relationWithList' => '', 'relationMethodList' => '', 'relationVisibleFieldList' => '']);
931 932 933 934
                //需要重写index方法
                $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
            }
935
            // 生成控制器文件
936
            $this->writeToFile('controller', $data, $controllerFile);
937
            // 生成模型文件
938
            $this->writeToFile('model', $data, $modelFile);
Karson authored
939 940 941 942 943 944

            if ($relations) {
                foreach ($relations as $i => $relation) {
                    $relation['modelNamespace'] = $data['modelNamespace'];
                    if (!is_file($relation['relationFile'])) {
                        // 生成关联模型文件
945
                        $this->writeToFile('relationmodel', $relation, $relation['relationFile']);
Karson authored
946 947
                    }
                }
948
            }
949
            // 生成验证文件
950
            $this->writeToFile('validate', $data, $validateFile);
951
            // 生成视图文件
952 953 954
            $this->writeToFile('add', $data, $addFile);
            $this->writeToFile('edit', $data, $editFile);
            $this->writeToFile('index', $data, $indexFile);
955
            if ($recyclebinHtml) {
956
                $this->writeToFile('recyclebin', $data, $recyclebinFile);
957 958 959 960
                $recyclebinTitle = in_array('title', $fieldArr) ? 'title' : (in_array('name', $fieldArr) ? 'name' : '');
                $recyclebinTitleJs = $recyclebinTitle ? "\n                        {field: '{$recyclebinTitle}', title: __('" . (ucfirst($recyclebinTitle)) . "'), align: 'left'}," : '';
                $data['recyclebinJs'] = $this->getReplacedStub('mixins/recyclebinjs', ['recyclebinTitleJs' => $recyclebinTitleJs, 'controllerUrl' => $controllerUrl]);
            }
961
            // 生成JS文件
962
            $this->writeToFile('javascript', $data, $javascriptFile);
963
            // 生成语言文件
964
            $this->writeToFile('lang', $data, $langFile);
965
        } catch (ErrorException $e) {
Karson authored
966
            throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
Karson authored
967
        }
Karson authored
968 969

        //继续生成菜单
Karson authored
970
        if ($menu) {
Karson authored
971 972 973
            exec("php think menu -c {$controllerUrl}");
        }
974
        $output->info("Build Successed");
Karson authored
975 976
    }
977
    protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
Karson authored
978
    {
979
        if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
Karson authored
980
            return;
981
        }
982
        $fieldList = $this->getFieldListName($field);
983
        $methodName = 'get' . ucfirst($fieldList);
Karson authored
984
        foreach ($itemArr as $k => &$v) {
985
            $v = "__('" . mb_ucfirst($v) . "')";
Karson authored
986
        }
987 988 989 990
        unset($v);
        $itemString = $this->getArrayString($itemArr);
        $getEnum[] = <<<EOD
    public function {$methodName}()
Karson authored
991
    {
992
        return [{$itemString}];
993
    }
994 995 996
EOD;
        $controllerAssignList[] = <<<EOD
        \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
Karson authored
997 998 999
EOD;
    }
1000
    protected function getAttr(&$getAttr, $field, $inputType = '')
Karson authored
1001
    {
1002
        if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
1003
            return;
1004
        }
1005
        $attrField = ucfirst($this->getCamelizeName($field));
1006 1007 1008 1009 1010
        $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
    }

    protected function setAttr(&$setAttr, $field, $inputType = '')
    {
1011
        if (!in_array($inputType, ['datetime', 'checkbox', 'select'])) {
Karson authored
1012
            return;
1013
        }
1014
        $attrField = ucfirst($this->getCamelizeName($field));
Karson authored
1015
        if ($inputType == 'datetime') {
Karson authored
1016
            $return = <<<EOD
1017
return \$value === '' ? null : (\$value && !is_numeric(\$value) ? strtotime(\$value) : \$value);
Karson authored
1018
EOD;
1019
        } elseif (in_array($inputType, ['checkbox', 'select'])) {
Karson authored
1020 1021 1022 1023
            $return = <<<EOD
return is_array(\$value) ? implode(',', \$value) : \$value;
EOD;
        }
Karson authored
1024
        $setAttr[] = <<<EOD
1025
    protected function set{$attrField}Attr(\$value)
Karson authored
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    {
        $return
    }
EOD;
    }

    protected function appendAttr(&$appendAttrList, $field)
    {
        $appendAttrList[] = <<<EOD
        '{$field}_text'
EOD;
    }
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    /**
     * 移除相对的空目录
     * @param $parseFile
     * @param $parseArr
     * @return bool
     */
    protected function removeEmptyBaseDir($parseFile, $parseArr)
    {
        if (count($parseArr) > 1) {
            $parentDir = dirname($parseFile);
            for ($i = 0; $i < count($parseArr); $i++) {
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
                try {
                    $iterator = new \FilesystemIterator($parentDir);
                    $isDirEmpty = !$iterator->valid();
                    if ($isDirEmpty) {
                        rmdir($parentDir);
                        $parentDir = dirname($parentDir);
                    } else {
                        return true;
                    }
                } catch (\UnexpectedValueException $e) {
                    return false;
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
                }
            }
        }
        return true;
    }

    /**
     * 获取控制器相关信息
     * @param $module
     * @param $controller
     * @param $table
     * @return array
     */
    protected function getControllerData($module, $controller, $table)
    {
        return $this->getParseNameData($module, $controller, $table, 'controller');
    }

    /**
     * 获取模型相关信息
     * @param $module
     * @param $model
     * @param $table
     * @return array
     */
    protected function getModelData($module, $model, $table)
1087
    {
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        return $this->getParseNameData($module, $model, $table, 'model');
    }

    /**
     * 获取验证器相关信息
     * @param $module
     * @param $validate
     * @param $table
     * @return array
     */
    protected function getValidateData($module, $validate, $table)
    {
        return $this->getParseNameData($module, $validate, $table, 'validate');
    }

    /**
     * 获取已解析相关信息
1105
     * @param string $module 模块名称
1106 1107 1108
     * @param string $name   自定义名称
     * @param string $table  数据表名
     * @param string $type   解析类型,本例中为controller、model、validate
1109 1110 1111 1112
     * @return array
     */
    protected function getParseNameData($module, $name, $table, $type)
    {
灰大狼 authored
1113
        $arr = [];
1114
        if (!$name) {
灰大狼 authored
1115 1116
            $parseName = Loader::parseName($table, 1);
            $parseArr = [$table];
1117
        } else {
1118 1119
            $name = str_replace(['.', '/', '\\'], '/', $name);
            $arr = explode('/', $name);
灰大狼 authored
1120 1121 1122
            $parseName = ucfirst(array_pop($arr));
            $parseArr = $arr;
            array_push($parseArr, $parseName);
1123
        }
1124 1125 1126 1127
        //类名不能为内部关键字
        if (in_array(strtolower($parseName), $this->internalKeywords)) {
            throw new Exception('Unable to use internal variable:' . $parseName);
        }
1128 1129 1130 1131
        $appNamespace = Config::get('app_namespace');
        $parseNamespace = "{$appNamespace}\\{$module}\\{$type}" . ($arr ? "\\" . implode("\\", $arr) : "");
        $moduleDir = APP_PATH . $module . DS;
        $parseFile = $moduleDir . $type . DS . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php';
1132
        return [$parseNamespace, $parseName, $parseFile, $parseArr];
1133 1134
    }
Karson authored
1135 1136 1137
    /**
     * 写入到文件
     * @param string $name
1138
     * @param array  $data
Karson authored
1139 1140 1141 1142 1143
     * @param string $pathname
     * @return mixed
     */
    protected function writeToFile($name, $data, $pathname)
    {
Karson authored
1144 1145 1146 1147
        foreach ($data as $index => &$datum) {
            $datum = is_array($datum) ? '' : $datum;
        }
        unset($datum);
1148 1149
        $content = $this->getReplacedStub($name, $data);
Karson authored
1150
        if (!is_dir(dirname($pathname))) {
1151
            mkdir(dirname($pathname), 0755, true);
1152 1153 1154 1155 1156 1157 1158
        }
        return file_put_contents($pathname, $content);
    }

    /**
     * 获取替换后的数据
     * @param string $name
1159
     * @param array  $data
1160 1161 1162 1163
     * @return string
     */
    protected function getReplacedStub($name, $data)
    {
Karson authored
1164 1165 1166 1167
        foreach ($data as $index => &$datum) {
            $datum = is_array($datum) ? '' : $datum;
        }
        unset($datum);
Karson authored
1168
        $search = $replace = [];
Karson authored
1169
        foreach ($data as $k => $v) {
Karson authored
1170 1171 1172
            $search[] = "{%{$k}%}";
            $replace[] = $v;
        }
1173
        $stubname = $this->getStub($name);
Karson authored
1174
        if (isset($this->stubList[$stubname])) {
1175
            $stub = $this->stubList[$stubname];
Karson authored
1176
        } else {
1177 1178
            $this->stubList[$stubname] = $stub = file_get_contents($stubname);
        }
Karson authored
1179
        $content = str_replace($search, $replace, $stub);
1180
        return $content;
Karson authored
1181 1182 1183 1184 1185 1186 1187 1188 1189
    }

    /**
     * 获取基础模板
     * @param string $name
     * @return string
     */
    protected function getStub($name)
    {
1190
        return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
Karson authored
1191 1192 1193 1194
    }

    protected function getLangItem($field, $content)
    {
Karson authored
1195
        if ($content || !Lang::has($field)) {
1196
            $this->fieldMaxLen = strlen($field) > $this->fieldMaxLen ? strlen($field) : $this->fieldMaxLen;
1197
            $content = str_replace(',', ',', $content);
Karson authored
1198
            if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false) {
1199 1200
                list($fieldLang, $item) = explode(':', $content);
                $itemArr = [$field => $fieldLang];
Karson authored
1201
                foreach (explode(',', $item) as $k => $v) {
1202
                    $valArr = explode('=', $v);
Karson authored
1203
                    if (count($valArr) == 2) {
1204 1205
                        list($key, $value) = $valArr;
                        $itemArr[$field . ' ' . $key] = $value;
1206
                        $this->fieldMaxLen = strlen($field . ' ' . $key) > $this->fieldMaxLen ? strlen($field . ' ' . $key) : $this->fieldMaxLen;
1207
                    }
1208
                }
Karson authored
1209
            } else {
1210 1211 1212
                $itemArr = [$field => $content];
            }
            $resultArr = [];
Karson authored
1213
            foreach ($itemArr as $k => $v) {
1214
                $resultArr[] = "    '" . mb_ucfirst($k) . "' => '{$v}'";
1215 1216
            }
            return implode(",\n", $resultArr);
Karson authored
1217
        } else {
Karson authored
1218 1219 1220 1221 1222
            return '';
        }
    }

    /**
1223
     * 读取数据和语言数组列表
1224
     * @param array   $arr
1225
     * @param boolean $withTpl
1226 1227
     * @return array
     */
1228
    protected function getLangArray($arr, $withTpl = true)
1229 1230
    {
        $langArr = [];
Karson authored
1231
        foreach ($arr as $k => $v) {
1232
            $langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
        }
        return $langArr;
    }

    /**
     * 将数据转换成带字符串
     * @param array $arr
     * @return string
     */
    protected function getArrayString($arr)
    {
1244
        if (!is_array($arr)) {
1245
            return $arr;
1246
        }
1247
        $stringArr = [];
Karson authored
1248
        foreach ($arr as $k => $v) {
1249
            $is_var = in_array(substr($v, 0, 1), ['$', '_']);
Karson authored
1250
            if (!$is_var) {
1251 1252 1253
                $v = str_replace("'", "\'", $v);
                $k = str_replace("'", "\'", $k);
            }
1254
            $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
1255
        }
1256
        return implode(", ", $stringArr);
1257 1258
    }
1259 1260 1261
    protected function getItemArray($item, $field, $comment)
    {
        $itemArr = [];
1262
        $comment = str_replace(',', ',', $comment);
Karson authored
1263
        if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
1264 1265
            list($fieldLang, $item) = explode(':', $comment);
            $itemArr = [];
Karson authored
1266
            foreach (explode(',', $item) as $k => $v) {
1267
                $valArr = explode('=', $v);
Karson authored
1268
                if (count($valArr) == 2) {
1269 1270 1271
                    list($key, $value) = $valArr;
                    $itemArr[$key] = $field . ' ' . $key;
                }
1272
            }
Karson authored
1273 1274
        } else {
            foreach ($item as $k => $v) {
1275 1276 1277 1278 1279 1280
                $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
            }
        }
        return $itemArr;
    }
1281 1282 1283
    protected function getFieldType(& $v)
    {
        $inputType = 'text';
Karson authored
1284
        switch ($v['DATA_TYPE']) {
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
            case 'bigint':
            case 'int':
            case 'mediumint':
            case 'smallint':
            case 'tinyint':
                $inputType = 'number';
                break;
            case 'enum':
            case 'set':
                $inputType = 'select';
                break;
            case 'decimal':
            case 'double':
            case 'float':
                $inputType = 'number';
                break;
            case 'longtext':
            case 'text':
            case 'mediumtext':
            case 'smalltext':
            case 'tinytext':
                $inputType = 'textarea';
                break;
1308 1309 1310 1311 1312
            case 'year':
            case 'date':
            case 'time':
            case 'datetime':
            case 'timestamp':
1313 1314 1315 1316 1317 1318
                $inputType = 'datetime';
                break;
            default:
                break;
        }
        $fieldsName = $v['COLUMN_NAME'];
Karson authored
1319
        // 指定后缀说明也是个时间字段
Karson authored
1320
        if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) {
1321 1322
            $inputType = 'datetime';
        }
Karson authored
1323
        // 指定后缀结尾且类型为enum,说明是个单选框
Karson authored
1324
        if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum') {
1325 1326
            $inputType = "radio";
        }
Karson authored
1327
        // 指定后缀结尾且类型为set,说明是个复选框
Karson authored
1328
        if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set') {
1329 1330
            $inputType = "checkbox";
        }
Karson authored
1331
        // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
Karson authored
1332
        if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null) {
Karson authored
1333 1334
            $inputType = "switch";
        }
Karson authored
1335
        // 指定后缀结尾城市选择框
Karson authored
1336
        if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
Karson authored
1337 1338
            $inputType = "citypicker";
        }
1339 1340 1341 1342
        // 指定后缀结尾JSON配置
        if ($this->isMatchSuffix($fieldsName, $this->jsonSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'text')) {
            $inputType = "fieldlist";
        }
1343 1344 1345 1346
        return $inputType;
    }

    /**
1347
     * 判断是否符合指定后缀
1348 1349
     * @param string $field     字段名称
     * @param mixed  $suffixArr 后缀
1350 1351 1352 1353 1354
     * @return boolean
     */
    protected function isMatchSuffix($field, $suffixArr)
    {
        $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
Karson authored
1355 1356
        foreach ($suffixArr as $k => $v) {
            if (preg_match("/{$v}$/i", $field)) {
1357 1358 1359 1360 1361 1362 1363
                return true;
            }
        }
        return false;
    }

    /**
Karson authored
1364 1365 1366 1367 1368 1369 1370
     * 获取表单分组数据
     * @param string $field
     * @param string $content
     * @return string
     */
    protected function getFormGroup($field, $content)
    {
1371
        $langField = mb_ucfirst($field);
Karson authored
1372
        return <<<EOD
Karson authored
1373
    <div class="form-group">
1374
        <label class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
Karson authored
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
        <div class="col-xs-12 col-sm-8">
            {$content}
        </div>
    </div>
EOD;
    }

    /**
     * 获取图片模板数据
     * @param string $field
     * @param string $content
1386
     * @return string
Karson authored
1387 1388 1389
     */
    protected function getImageUpload($field, $content)
    {
Karson authored
1390
        $uploadfilter = $selectfilter = '';
Karson authored
1391
        if ($this->isMatchSuffix($field, $this->imageField)) {
Karson authored
1392 1393
            $uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"';
            $selectfilter = ' data-mimetype="image/*"';
Karson authored
1394
        }
1395
        $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
1396
        $preview = ' data-preview-id="p-' . $field . '"';
1397
        $previewcontainer = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $field . '"></ul>' : '';
Karson authored
1398
        return <<<EOD
1399
<div class="input-group">
Karson authored
1400
                {$content}
1401 1402 1403 1404
                <div class="input-group-addon no-border no-padding">
                    <span><button type="button" id="plupload-{$field}" class="btn btn-danger plupload" data-input-id="c-{$field}"{$uploadfilter}{$multiple}{$preview}><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
                    <span><button type="button" id="fachoose-{$field}" class="btn btn-primary fachoose" data-input-id="c-{$field}"{$selectfilter}{$multiple}><i class="fa fa-list"></i> {:__('Choose')}</button></span>
                </div>
1405
                <span class="msg-box n-right" for="c-{$field}"></span>
Karson authored
1406
            </div>
1407
            {$previewcontainer}
Karson authored
1408 1409 1410 1411 1412 1413
EOD;
    }

    /**
     * 获取JS列数据
     * @param string $field
1414 1415
     * @param string $datatype
     * @param string $extend
1416
     * @param array  $itemArr
Karson authored
1417 1418
     * @return string
     */
1419
    protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = [])
Karson authored
1420
    {
1421
        $lang = mb_ucfirst($field);
Karson authored
1422
        $formatter = '';
Karson authored
1423 1424 1425 1426
        foreach ($this->fieldFormatterSuffix as $k => $v) {
            if (preg_match("/{$k}$/i", $field)) {
                if (is_array($v)) {
                    if (in_array($datatype, $v['type'])) {
Karson authored
1427 1428 1429
                        $formatter = $v['name'];
                        break;
                    }
Karson authored
1430
                } else {
Karson authored
1431 1432 1433 1434 1435
                    $formatter = $v;
                    break;
                }
            }
        }
1436 1437 1438 1439
        $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";

        if ($datatype == 'set') {
            $formatter = 'label';
1440
        }
Karson authored
1441
        foreach ($itemArr as $k => &$v) {
1442
            if (substr($v, 0, 3) !== '__(') {
1443
                $v = "__('" . mb_ucfirst($v) . "')";
1444
            }
1445 1446
        }
        unset($v);
1447
        $searchList = json_encode($itemArr, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
1448
        $searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList);
1449
        if ($itemArr) {
1450 1451
            $html .= ", searchList: " . $searchList;
        }
Karson authored
1452
        if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime') {
1453
            $html .= ", operate:'RANGE', addclass:'datetimerange'";
1454
        } elseif (in_array($datatype, ['float', 'double', 'decimal'])) {
1455 1456
            $html .= ", operate:'BETWEEN'";
        }
1457 1458 1459
        if (in_array($datatype, ['set'])) {
            $html .= ", operate:'FIND_IN_SET'";
        }
1460
        if (in_array($formatter, ['image', 'images'])) {
1461 1462
            $html .= ", events: Table.api.events.image";
        }
1463 1464 1465
        if (in_array($formatter, ['toggle'])) {
            $html .= ", table: table";
        }
1466 1467 1468
        if ($itemArr && !$formatter) {
            $formatter = 'normal';
        }
1469
        if ($formatter) {
Karson authored
1470
            $html .= ", formatter: Table.api.formatter." . $formatter . "}";
1471
        } else {
Karson authored
1472
            $html .= "}";
1473
        }
Karson authored
1474 1475 1476
        return $html;
    }
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
    protected function getCamelizeName($uncamelized_words, $separator = '_')
    {
        $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
        return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
    }

    protected function getFieldListName($field)
    {
        return $this->getCamelizeName($field) . 'List';
    }
Karson authored
1487
}