审查视图

application/admin/command/Crud.php 52.2 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;
Karson authored
13 14 15 16 17
use think\Lang;

class Crud extends Command
{
18 19
    protected $stubList = [];
Karson authored
20 21 22 23 24 25 26 27 28 29
    /**
     * Selectpage搜索字段关联
     */
    protected $fieldSelectpageMap = [
        'nickname' => ['user_id', 'user_ids', 'admin_id', 'admin_ids']
    ];

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

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

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

    /**
Karson authored
43
     * 开关后缀
Karson authored
44
     */
45 46 47
    protected $switchSuffix = ['switch'];

    /**
Karson authored
48 49 50 51 52
     * 城市后缀
     */
    protected $citySuffix = ['city'];

    /**
53 54 55 56 57 58 59 60
     * Selectpage对应的后缀
     */
    protected $selectpageSuffix = ['_id', '_ids'];

    /**
     * Selectpage多选对应的后缀
     */
    protected $selectpagesSuffix = ['_ids'];
Karson authored
61 62 63 64 65

    /**
     * 以指定字符结尾的字段格式化函数
     */
    protected $fieldFormatterSuffix = [
66
        'status' => ['type' => ['varchar'], 'name' => 'status'],
Karson authored
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
        'icon'   => 'icon',
        'flag'   => 'flag',
        'url'    => 'url',
        'image'  => 'image',
        'images' => 'images',
        'time'   => ['type' => ['int', 'timestamp'], 'name' => 'datetime']
    ];

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

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

    /**
     * 保留字段
     */
Karson authored
88
    protected $reservedField = ['admin_id', 'createtime', 'updatetime'];
Karson authored
89 90

    /**
91 92 93 94 95
     * 排除字段
     */
    protected $ignoreFields = [];

    /**
Karson authored
96 97 98 99 100 101 102
     * 排序字段
     */
    protected $sortField = 'weigh';

    /**
     * 编辑器的Class
     */
Karson authored
103
    protected $editorClass = 'editor';
Karson authored
104
Karson authored
105 106 107 108 109 110 111 112 113
    protected function configure()
    {
        $this
                ->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('force', 'f', Option::VALUE_OPTIONAL, 'force override', null)
                ->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local model', 1)
114 115 116 117
                ->addOption('relation', 'r', Option::VALUE_OPTIONAL, 'relation table name without prefix', null)
                ->addOption('relationmodel', 'e', Option::VALUE_OPTIONAL, 'relation model name', null)
                ->addOption('relationforeignkey', 'k', Option::VALUE_OPTIONAL, 'relation foreign key', null)
                ->addOption('relationprimarykey', 'p', Option::VALUE_OPTIONAL, 'relation primary key', null)
118 119
                ->addOption('mode', 'o', Option::VALUE_OPTIONAL, 'relation table mode,hasone or belongsto', 'belongsto')
                ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete all files generated by CRUD', null)
Karson authored
120
                ->addOption('menu', 'u', Option::VALUE_OPTIONAL, 'create menu when CRUD completed', null)
121 122 123 124 125 126
                ->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)
Karson authored
127
                ->addOption('citysuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate citypicker component with suffix', null)
128 129
                ->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)
130
                ->addOption('ignorefields', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'ignore fields', null)
131 132
                ->addOption('sortfield', null, Option::VALUE_OPTIONAL, 'sort field', null)
                ->addOption('editorclass', null, Option::VALUE_OPTIONAL, 'automatically generate editor class', null)
Karson authored
133 134 135 136 137 138 139
                ->setDescription('Build CRUD controller and model from table');
    }

    protected function execute(Input $input, Output $output)
    {
        $adminPath = dirname(__DIR__) . DS;
        //表名
140
        $table = $input->getOption('table') ?: '';
Karson authored
141 142 143 144 145 146 147 148 149 150
        //自定义控制器
        $controller = $input->getOption('controller');
        //自定义模型
        $model = $input->getOption('model');
        //强制覆盖
        $force = $input->getOption('force');
        //是否为本地model,为0时表示为全局model将会把model放在app/common/model中
        $local = $input->getOption('local');
        if (!$table)
        {
151
            throw new Exception('table name can\'t empty');
Karson authored
152
        }
Karson authored
153 154
        //是否生成菜单
        $menu = $input->getOption("menu");
155 156 157 158 159 160 161 162 163 164
        //关联表
        $relation = $input->getOption('relation');
        //自定义关联表模型
        $relationModel = $input->getOption('relationmodel');
        //模式
        $mode = $input->getOption('mode');
        //外键
        $relationForeignKey = $input->getOption('relationforeignkey');
        //主键
        $relationPrimaryKey = $input->getOption('relationprimarykey');
165 166 167 168 169 170 171 172 173 174 175 176
        //复选框后缀
        $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
177 178
        //城市后缀
        $citysuffix = $input->getOption('citysuffix');
179 180 181 182
        //selectpage后缀
        $selectpagesuffix = $input->getOption('selectpagesuffix');
        //selectpage多选后缀
        $selectpagessuffix = $input->getOption('selectpagessuffix');
183 184
        //排除字段
        $ignoreFields = $input->getOption('ignorefields');
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        //排序字段
        $sortfield = $input->getOption('sortfield');
        //编辑器Class
        $editorclass = $input->getOption('editorclass');
        if ($setcheckboxsuffix)
            $this->setCheckboxSuffix = $setcheckboxsuffix;
        if ($enumradiosuffix)
            $this->enumRadioSuffix = $enumradiosuffix;
        if ($imagefield)
            $this->imageField = $imagefield;
        if ($filefield)
            $this->fileField = $filefield;
        if ($intdatesuffix)
            $this->intDateSuffix = $intdatesuffix;
        if ($switchsuffix)
            $this->switchSuffix = $switchsuffix;
Karson authored
201 202
        if ($citysuffix)
            $this->citySuffix = $citysuffix;
203 204 205 206
        if ($selectpagesuffix)
            $this->selectpageSuffix = $selectpagesuffix;
        if ($selectpagessuffix)
            $this->selectpagesSuffix = $selectpagessuffix;
207 208
        if ($ignoreFields)
            $this->ignoreFields = $ignoreFields;
209 210 211 212 213
        if ($editorclass)
            $this->editorClass = $editorclass;
        if ($sortfield)
            $this->sortField = $sortfield;
214 215 216 217 218 219
        //如果有启用关联模式
        if ($relation && !in_array($mode, ['hasone', 'belongsto']))
        {
            throw new Exception("relation table only work in hasone or belongsto mode");
        }
Karson authored
220 221
        $dbname = Config::get('database.database');
        $prefix = Config::get('database.prefix');
222 223

        //检查主表
224 225
        $table = stripos($table, $prefix) === 0 ? substr($table, strlen($prefix)) : $table;
        $modelTableName = $tableName = $table;
226
        $modelTableType = 'table';
Karson authored
227 228 229
        $tableInfo = Db::query("SHOW TABLE STATUS LIKE '{$tableName}'", [], TRUE);
        if (!$tableInfo)
        {
230 231 232 233 234 235 236
            $tableName = $prefix . $table;
            $modelTableType = 'name';
            $tableInfo = Db::query("SHOW TABLE STATUS LIKE '{$tableName}'", [], TRUE);
            if (!$tableInfo)
            {
                throw new Exception("table not found");
            }
Karson authored
237 238
        }
        $tableInfo = $tableInfo[0];
239
240
        $relationModelTableName = $relationTableName = $relation;
241
        $relationModelTableType = 'table';
242 243 244
        //检查关联表
        if ($relation)
        {
245 246
            $relation = stripos($relation, $prefix) === 0 ? substr($relation, strlen($prefix)) : $relation;
            $relationModelTableName = $relationTableName = $relation;
247 248 249
            $relationTableInfo = Db::query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], TRUE);
            if (!$relationTableInfo)
            {
250
                $relationTableName = $prefix . $relation;
251 252 253 254 255 256
                $relationModelTableType = 'name';
                $relationTableInfo = Db::query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], TRUE);
                if (!$relationTableInfo)
                {
                    throw new Exception("relation table not found");
                }
257 258 259
            }
        }
Karson authored
260
        //根据表名匹配对应的Fontawesome图标
261
        $iconPath = ROOT_PATH . str_replace('/', DS, '/public/assets/libs/font-awesome/less/variables.less');
262
        $iconName = is_file($iconPath) && stripos(file_get_contents($iconPath), '@fa-var-' . $table . ':') ? 'fa fa-' . $table : 'fa fa-circle-o';
Karson authored
263 264

        //控制器默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入controller,格式为目录层级
265
        $controller = str_replace('_', '', $controller);
Karson authored
266 267
        $controllerArr = !$controller ? explode('_', strtolower($table)) : explode('/', strtolower($controller));
        $controllerUrl = implode('/', $controllerArr);
268
        $controllerName = ucfirst(array_pop($controllerArr));
269 270
        $controllerDir = implode(DS, $controllerArr);
        $controllerFile = ($controllerDir ? $controllerDir . DS : '') . $controllerName . '.php';
271
        $viewDir = $adminPath . 'view' . DS . $controllerUrl . DS;
Karson authored
272
273 274 275 276 277 278 279
        //最终将生成的文件路径
        $controllerFile = $adminPath . 'controller' . DS . $controllerFile;
        $javascriptFile = ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend' . DS . $controllerUrl . '.js';
        $addFile = $viewDir . 'add.html';
        $editFile = $viewDir . 'edit.html';
        $indexFile = $viewDir . 'index.html';
        $langFile = $adminPath . 'lang' . DS . Lang::detect() . DS . $controllerUrl . '.php';
Karson authored
280 281

        //模型默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入model,不支持目录层级
282
        $modelName = $this->getModelName($model, $table);
Karson authored
283 284
        $modelFile = ($local ? $adminPath : APP_PATH . 'common' . DS) . 'model' . DS . $modelName . '.php';
285 286
        $validateFile = $adminPath . 'validate' . DS . $modelName . '.php';
287 288 289 290
        //关联模型默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入relationmodel,不支持目录层级
        $relationModelName = $this->getModelName($relationModel, $relation);
        $relationModelFile = ($local ? $adminPath : APP_PATH . 'common' . DS) . 'model' . DS . $relationModelName . '.php';
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
        //是否为删除模式
        $delete = $input->getOption('delete');
        if ($delete)
        {
            $readyFiles = [$controllerFile, $modelFile, $validateFile, $addFile, $editFile, $indexFile, $langFile, $javascriptFile];
            foreach ($readyFiles as $k => $v)
            {
                $output->warning($v);
            }
            $output->info("Are you sure you want to delete all those files?  Type 'yes' to continue: ");
            $line = fgets(STDIN);
            if (trim($line) != 'yes')
            {
                throw new Exception("Operation is aborted!");
            }
            foreach ($readyFiles as $k => $v)
            {
Karson authored
308 309
                if (file_exists($v))
                    unlink($v);
310 311 312 313 314 315 316 317 318 319 320 321
            }

            $output->info("Delete Successed");
            return;
        }

        //非覆盖模式时如果存在控制器文件则报错
        if (is_file($controllerFile) && !$force)
        {
            throw new Exception("controller already exists!\nIf you need to rebuild again, use the parameter --force=true ");
        }
Karson authored
322 323 324
        //非覆盖模式时如果存在模型文件则报错
        if (is_file($modelFile) && !$force)
        {
325 326 327 328 329 330 331
            throw new Exception("model already exists!\nIf you need to rebuild again, use the parameter --force=true ");
        }

        //非覆盖模式时如果存在验证文件则报错
        if (is_file($validateFile) && !$force)
        {
            throw new Exception("validate already exists!\nIf you need to rebuild again, use the parameter --force=true ");
Karson authored
332 333
        }
334 335
        require $adminPath . 'common.php';
Karson authored
336
        //从数据库中获取表字段信息
337 338 339 340 341 342 343 344 345
        $sql = "SELECT * FROM `information_schema`.`columns` "
                . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
                . "ORDER BY ORDINAL_POSITION";
        $columnList = Db::query($sql, [$dbname, $tableName]);
        $relationColumnList = [];
        if ($relation)
        {
            $relationColumnList = Db::query($sql, [$dbname, $relationTableName]);
        }
346
347
        $fieldArr = [];
Karson authored
348 349
        foreach ($columnList as $k => $v)
        {
350 351 352 353 354 355 356
            $fieldArr[] = $v['COLUMN_NAME'];
        }

        $relationFieldArr = [];
        foreach ($relationColumnList as $k => $v)
        {
            $relationFieldArr[] = $v['COLUMN_NAME'];
Karson authored
357 358 359 360 361 362 363 364
        }

        $addList = [];
        $editList = [];
        $javascriptList = [];
        $langList = [];
        $field = 'id';
        $order = 'id';
365
        $priDefined = FALSE;
366 367
        $priKey = '';
        $relationPriKey = '';
368 369 370 371
        foreach ($columnList as $k => $v)
        {
            if ($v['COLUMN_KEY'] == 'PRI')
            {
372
                $priKey = $v['COLUMN_NAME'];
373 374 375
                break;
            }
        }
376
        if (!$priKey)
377 378 379
        {
            throw new Exception('Primary key not found!');
        }
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
        if ($relation)
        {
            foreach ($relationColumnList as $k => $v)
            {
                if ($v['COLUMN_KEY'] == 'PRI')
                {
                    $relationPriKey = $v['COLUMN_NAME'];
                    break;
                }
            }
            if (!$relationPriKey)
            {
                throw new Exception('Relation Primary key not found!');
            }
        }
        $order = $priKey;


        //如果是关联模型
        if ($relation)
        {
            if ($mode == 'hasone')
            {
                $relationForeignKey = $relationForeignKey ? $relationForeignKey : $table . "_id";
                $relationPrimaryKey = $relationPrimaryKey ? $relationPrimaryKey : $priKey;
                if (!in_array($relationForeignKey, $relationFieldArr))
                {
                    throw new Exception('relation table must be contain field:' . $relationForeignKey);
                }
                if (!in_array($relationPrimaryKey, $fieldArr))
                {
                    throw new Exception('table must be contain field:' . $relationPrimaryKey);
                }
            }
            else
            {
                $relationForeignKey = $relationForeignKey ? $relationForeignKey : $relation . "_id";
                $relationPrimaryKey = $relationPrimaryKey ? $relationPrimaryKey : $relationPriKey;
                if (!in_array($relationForeignKey, $fieldArr))
                {
                    throw new Exception('table must be contain field:' . $relationForeignKey);
                }
                if (!in_array($relationPrimaryKey, $relationFieldArr))
                {
                    throw new Exception('relation table must be contain field:' . $relationPrimaryKey);
                }
            }
        }
Karson authored
428
429
        try
Karson authored
430
        {
431
            Form::setEscapeHtml(false);
Karson authored
432 433
            $setAttrArr = [];
            $getAttrArr = [];
434
            $getEnumArr = [];
Karson authored
435
            $appendAttrList = [];
436
            $controllerAssignList = [];
437 438 439

            //循环所有字段,开始构造视图的HTML和JS信息
            foreach ($columnList as $k => $v)
Karson authored
440
            {
441 442 443 444
                $field = $v['COLUMN_NAME'];
                $itemArr = [];
                // 这里构建Enum和Set类型的列表数据
                if (in_array($v['DATA_TYPE'], ['enum', 'set']))
Karson authored
445
                {
446 447
                    $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
                    $itemArr = explode(',', str_replace("'", '', $itemArr));
448
                    $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
Karson authored
449
                }
450 451
                // 语言列表
                if ($v['COLUMN_COMMENT'] != '')
Karson authored
452
                {
453
                    $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
Karson authored
454
                }
455
                $inputType = '';
456
                //createtime和updatetime是保留字段不能修改和添加
457
                if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $this->reservedField) && !in_array($field, $this->ignoreFields))
Karson authored
458
                {
459 460 461 462 463 464 465 466 467 468
                    $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'];
                    $editValue = "{\$row.{$field}}";
469
                    // 如果默认值非null,则是一个必选项
Karson authored
470
                    if ($v['IS_NULLABLE'] == 'NO')
Karson authored
471
                    {
Karson authored
472
                        $attrArr['data-rule'] = 'required';
Karson authored
473
                    }
474
475
                    if ($inputType == 'select')
Karson authored
476
                    {
477 478 479 480 481
                        $cssClassArr[] = 'selectpicker';
                        $attrArr['class'] = implode(' ', $cssClassArr);
                        if ($v['DATA_TYPE'] == 'set')
                        {
                            $attrArr['multiple'] = '';
482
                            $fieldName .= "[]";
483
                        }
484 485 486
                        $attrArr['name'] = $fieldName;

                        $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
Karson authored
487
488
                        $itemArr = $this->getLangArray($itemArr, FALSE);
Karson authored
489
                        //添加一个获取器
490
                        $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
Karson authored
491 492 493 494
                        if ($v['DATA_TYPE'] == 'set')
                        {
                            $this->setAttr($setAttrArr, $field, $inputType);
                        }
Karson authored
495
                        $this->appendAttr($appendAttrList, $field);
496 497
                        $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}"]);
Karson authored
498
                    }
499
                    else if ($inputType == 'datetime')
Karson authored
500
                    {
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
                        $cssClassArr[] = 'datetimepicker';
                        $attrArr['class'] = implode(' ', $cssClassArr);
                        $format = "YYYY-MM-DD HH:mm:ss";
                        $phpFormat = "Y-m-d H:i:s";
                        $fieldFunc = '';
                        switch ($v['DATA_TYPE'])
                        {
                            case 'year';
                                $format = "YYYY";
                                $phpFormat = 'Y';
                                break;
                            case 'date';
                                $format = "YYYY-MM-DD";
                                $phpFormat = 'Y-m-d';
                                break;
                            case 'time';
                                $format = "HH:mm:ss";
                                $phpFormat = 'H:i:s';
                                break;
                            case 'timestamp';
                                $fieldFunc = 'datetime';
                            case 'datetime';
                                $format = "YYYY-MM-DD HH:mm:ss";
                                $phpFormat = 'Y-m-d H:i:s';
                                break;
                            default:
                                $fieldFunc = 'datetime';
528 529
                                $this->getAttr($getAttrArr, $field, $inputType);
                                $this->setAttr($setAttrArr, $field, $inputType);
Karson authored
530
                                $this->appendAttr($appendAttrList, $field);
531 532 533 534 535 536 537 538
                                break;
                        }
                        $defaultDateTime = "{:date('{$phpFormat}')}";
                        $attrArr['data-date-format'] = $format;
                        $attrArr['data-use-current'] = "true";
                        $fieldFunc = $fieldFunc ? "|{$fieldFunc}" : "";
                        $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
                        $formEditElement = Form::text($fieldName, "{\$row.{$field}{$fieldFunc}}", $attrArr);
Karson authored
539
                    }
540
                    else if ($inputType == 'checkbox' || $inputType == 'radio')
Karson authored
541
                    {
542
                        unset($attrArr['data-rule']);
543 544
                        $fieldName = $inputType == 'checkbox' ? $fieldName .= "[]" : $fieldName;
                        $attrArr['name'] = "row[{$fieldName}]";
545
546
                        $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $inputType);
547
                        $itemArr = $this->getLangArray($itemArr, FALSE);
Karson authored
548
                        //添加一个获取器
549
                        $this->getAttr($getAttrArr, $field, $inputType);
Karson authored
550 551 552 553
                        if ($inputType == 'checkbox')
                        {
                            $this->setAttr($setAttrArr, $field, $inputType);
                        }
Karson authored
554
                        $this->appendAttr($appendAttrList, $field);
555 556 557 558
                        $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}"]);
Karson authored
559
                    }
Karson authored
560
                    else if ($inputType == 'textarea')
Karson authored
561
                    {
Karson authored
562
                        $cssClassArr[] = substr($field, -7) == 'content' ? $this->editorClass : '';
563 564 565 566
                        $attrArr['class'] = implode(' ', $cssClassArr);
                        $attrArr['rows'] = 5;
                        $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr);
                        $formEditElement = Form::textarea($fieldName, $editValue, $attrArr);
Karson authored
567
                    }
Karson authored
568
                    else if ($inputType == 'switch')
Karson authored
569
                    {
570
                        unset($attrArr['data-rule']);
Karson authored
571
                        if ($defaultValue === '1' || $defaultValue === 'Y')
572
                        {
Karson authored
573 574 575 576 577 578 579
                            $yes = $defaultValue;
                            $no = $defaultValue === '1' ? '0' : 'N';
                        }
                        else
                        {
                            $no = $defaultValue;
                            $yes = $defaultValue === '0' ? '1' : 'Y';
580
                        }
Karson authored
581 582
                        $formAddElement = $formEditElement = Form::hidden($fieldName, $no, array_merge(['checked' => ''], $attrArr));
                        $attrArr['id'] = $fieldName . "-switch";
583 584
                        $formAddElement .= sprintf(Form::label("{$attrArr['id']}", "%s {:__('Yes')}", ['class'=>'control-label']), Form::checkbox($fieldName, $yes, $defaultValue === $yes, $attrArr));
                        $formEditElement .= sprintf(Form::label("{$attrArr['id']}", "%s {:__('Yes')}", ['class'=>'control-label']), Form::checkbox($fieldName, $yes, 0, $attrArr));
Karson authored
585
                        $formEditElement = str_replace('type="checkbox"', 'type="checkbox" {in name="' . "\$row.{$field}" . '" value="' . $yes . '"}checked{/in}', $formEditElement);
Karson authored
586
                    }
Karson authored
587 588 589 590 591 592 593
                    else if ($inputType == 'citypicker')
                    {
                        $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));
                    }
594
                    else
Karson authored
595
                    {
Karson authored
596 597
                        $search = $replace = '';
                        //特殊字段为关联搜索
598
                        if ($this->isMatchSuffix($field, $this->selectpageSuffix))
Karson authored
599 600 601 602 603
                        {
                            $inputType = 'text';
                            $defaultValue = '';
                            $attrArr['data-rule'] = 'required';
                            $cssClassArr[] = 'selectpage';
604 605
                            $selectpageController = str_replace('_', '/', substr($field, 0, strripos($field, '_')));
                            $attrArr['data-source'] = $selectpageController . "/index";
606
                            //如果是类型表需要特殊处理下
607
                            if ($selectpageController == 'category')
Karson authored
608
                            {
609
                                $attrArr['data-source'] = 'category/selectpage';
Karson authored
610 611 612 613
                                $attrArr['data-params'] = '##replacetext##';
                                $search = '"##replacetext##"';
                                $replace = '\'{"custom[type]":"' . $table . '"}\'';
                            }
614
                            if ($this->isMatchSuffix($field, $this->selectpagesSuffix))
Karson authored
615 616 617 618 619 620 621 622 623 624 625 626
                            {
                                $attrArr['data-multiple'] = 'true';
                            }
                            foreach ($this->fieldSelectpageMap as $m => $n)
                            {
                                if (in_array($field, $n))
                                {
                                    $attrArr['data-field'] = $m;
                                    break;
                                }
                            }
                        }
627
                        //因为有自动完成可输入其它内容
Karson authored
628
                        $step = array_intersect($cssClassArr, ['selectpage']) ? 0 : $step;
629
                        $attrArr['class'] = implode(' ', $cssClassArr);
Karson authored
630
                        $isUpload = false;
631
                        if ($this->isMatchSuffix($field, array_merge($this->imageField, $this->fileField)))
Karson authored
632
                        {
633
                            $isUpload = true;
Karson authored
634
                        }
635 636 637 638 639 640 641 642 643 644 645 646 647
                        //如果是步长则加上步长
                        if ($step)
                        {
                            $attrArr['step'] = $step;
                        }
                        //如果是图片加上个size
                        if ($isUpload)
                        {
                            $attrArr['size'] = 50;
                        }

                        $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
                        $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
Karson authored
648 649 650 651 652
                        if ($search && $replace)
                        {
                            $formAddElement = str_replace($search, $replace, $formAddElement);
                            $formEditElement = str_replace($search, $replace, $formEditElement);
                        }
653 654 655 656 657 658
                        //如果是图片或文件
                        if ($isUpload)
                        {
                            $formAddElement = $this->getImageUpload($field, $formAddElement);
                            $formEditElement = $this->getImageUpload($field, $formEditElement);
                        }
Karson authored
659
                    }
660 661 662
                    //构造添加和编辑HTML信息
                    $addList[] = $this->getFormGroup($field, $formAddElement);
                    $editList[] = $this->getFormGroup($field, $formEditElement);
Karson authored
663 664
                }
665 666
                //过滤text类型字段
                if ($v['DATA_TYPE'] != 'text')
Karson authored
667
                {
668 669 670 671
                    //主键
                    if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined)
                    {
                        $priDefined = TRUE;
672
                        $javascriptList[] = "{checkbox: true}";
673 674
                    }
                    //构造JS列信息
675
                    $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr);
676
Karson authored
677 678
                    //排序方式,如果有指定排序字段,否则按主键排序
                    $order = $field == $this->sortField ? $this->sortField : $order;
Karson authored
679
                }
680
            }
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699

            $relationPriKey = 'id';
            $relationFieldArr = [];
            foreach ($relationColumnList as $k => $v)
            {
                $relationField = $v['COLUMN_NAME'];
                $relationFieldArr[] = $field;

                $relationField = strtolower($relationModelName) . "." . $relationField;
                // 语言列表
                if ($v['COLUMN_COMMENT'] != '')
                {
                    $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
                }

                //过滤text类型字段
                if ($v['DATA_TYPE'] != 'text')
                {
                    //构造JS列信息
700
                    $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']);
701 702 703
                }
            }
704
            //JS最后一列加上操作列
705
            $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
706 707 708 709 710 711 712 713 714 715 716 717 718
            $addList = implode("\n", array_filter($addList));
            $editList = implode("\n", array_filter($editList));
            $javascriptList = implode(",\n", array_filter($javascriptList));
            $langList = implode(",\n", array_filter($langList));

            //表注释
            $tableComment = $tableInfo['Comment'];
            $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;

            $appNamespace = Config::get('app_namespace');
            $moduleName = 'admin';
            $controllerNamespace = "{$appNamespace}\\{$moduleName}\\controller" . ($controllerDir ? "\\" : "") . str_replace('/', "\\", $controllerDir);
            $modelNamespace = "{$appNamespace}\\" . ($local ? $moduleName : "common") . "\\model";
719 720
            $validateNamespace = "{$appNamespace}\\" . $moduleName . "\\validate";
            $validateName = $modelName;
721
722 723 724 725 726 727
            $modelInit = '';
            if ($priKey != $order)
            {
                $modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]);
            }
728 729 730
            $data = [
                'controllerNamespace'     => $controllerNamespace,
                'modelNamespace'          => $modelNamespace,
731
                'validateNamespace'       => $validateNamespace,
732 733 734
                'controllerUrl'           => $controllerUrl,
                'controllerDir'           => $controllerDir,
                'controllerName'          => $controllerName,
735
                'controllerAssignList'    => implode("\n", $controllerAssignList),
736
                'modelName'               => $modelName,
737
                'validateName'            => $validateName,
738 739
                'tableComment'            => $tableComment,
                'iconName'                => $iconName,
740
                'pk'                      => $priKey,
741 742 743 744 745 746 747
                'order'                   => $order,
                'table'                   => $table,
                'tableName'               => $tableName,
                'addList'                 => $addList,
                'editList'                => $editList,
                'javascriptList'          => $javascriptList,
                'langList'                => $langList,
748 749 750
                'modelAutoWriteTimestamp' => in_array('createtime', $fieldArr) || in_array('updatetime', $fieldArr) ? "'int'" : 'false',
                'createTime'              => in_array('createtime', $fieldArr) ? "'createtime'" : 'false',
                'updateTime'              => in_array('updatetime', $fieldArr) ? "'updatetime'" : 'false',
751
                'modelTableName'          => $modelTableName,
752
                'modelTableType'          => $modelTableType,
753
                'relationModelTableName'  => $relationModelTableName,
754
                'relationModelTableType'  => $relationModelTableType,
755 756 757 758 759 760 761 762
                'relationModelName'       => $relationModelName,
                'relationWith'            => '',
                'relationMethod'          => '',
                'relationModel'           => '',
                'relationForeignKey'      => '',
                'relationPrimaryKey'      => '',
                'relationSearch'          => $relation ? 'true' : 'false',
                'controllerIndex'         => '',
Karson authored
763
                'appendAttrList'          => implode(",\n", $appendAttrList),
764
                'getEnumList'             => implode("\n\n", $getEnumArr),
Karson authored
765 766
                'getAttrList'             => implode("\n\n", $getAttrArr),
                'setAttrList'             => implode("\n\n", $setAttrArr),
767 768
                'modelInit'               => $modelInit,
                'modelRelationMethod'     => '',
769 770
            ];
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
            //如果使用关联模型
            if ($relation)
            {
                //需要构造关联的方法
                $data['relationMethod'] = strtolower($relationModelName);
                //预载入的方法
                $data['relationWith'] = "->with('{$data['relationMethod']}')";
                //需要重写index方法
                $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
                //关联的模式
                $data['relationMode'] = $mode == 'hasone' ? 'hasOne' : 'belongsTo';
                //关联字段
                $data['relationForeignKey'] = $relationForeignKey;
                $data['relationPrimaryKey'] = $relationPrimaryKey ? $relationPrimaryKey : $priKey;
                //构造关联模型的方法
786
                $data['modelRelationMethod'] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod', $data);
787 788
            }
789 790 791 792
            // 生成控制器文件
            $result = $this->writeToFile('controller', $data, $controllerFile);
            // 生成模型文件
            $result = $this->writeToFile('model', $data, $modelFile);
793 794 795 796 797
            if ($relation && !is_file($relationModelFile))
            {
                // 生成关联模型文件
                $result = $this->writeToFile('relationmodel', $data, $relationModelFile);
            }
798 799
            // 生成验证文件
            $result = $this->writeToFile('validate', $data, $validateFile);
800 801 802 803 804 805 806 807 808 809
            // 生成视图文件
            $result = $this->writeToFile('add', $data, $addFile);
            $result = $this->writeToFile('edit', $data, $editFile);
            $result = $this->writeToFile('index', $data, $indexFile);
            // 生成JS文件
            $result = $this->writeToFile('javascript', $data, $javascriptFile);
            // 生成语言文件
            if ($langList)
            {
                $result = $this->writeToFile('lang', $data, $langFile);
Karson authored
810 811
            }
        }
812
        catch (\think\exception\ErrorException $e)
Karson authored
813
        {
Karson authored
814
            throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
Karson authored
815
        }
Karson authored
816 817 818 819 820 821 822

        //继续生成菜单
        if ($menu)
        {
            exec("php think menu -c {$controllerUrl}");
        }
823
        $output->info("Build Successed");
Karson authored
824 825
    }
826
    protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
Karson authored
827 828 829
    {
        if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
            return;
830
        $fieldList = $this->getFieldListName($field);
831
        $methodName = 'get' . ucfirst($fieldList);
832
        foreach ($itemArr as $k => &$v)
Karson authored
833
        {
834
            $v = "__('" . mb_ucfirst($v) . "')";
Karson authored
835
        }
836 837 838 839
        unset($v);
        $itemString = $this->getArrayString($itemArr);
        $getEnum[] = <<<EOD
    public function {$methodName}()
Karson authored
840
    {
841 842 843 844 845
        return [{$itemString}];
    }     
EOD;
        $controllerAssignList[] = <<<EOD
        \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
Karson authored
846 847 848
EOD;
    }
849
    protected function getAttr(&$getAttr, $field, $inputType = '')
Karson authored
850
    {
851
        if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
852
            return;
853
        $attrField = ucfirst($this->getCamelizeName($field));
854 855 856 857 858
        $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
    }

    protected function setAttr(&$setAttr, $field, $inputType = '')
    {
Karson authored
859
        if (!in_array($inputType, ['datetime', 'checkbox', 'select']))
Karson authored
860
            return;
861
        $attrField = ucfirst($this->getCamelizeName($field));
Karson authored
862 863 864
        if ($inputType == 'datetime')
        {
            $return = <<<EOD
865
return \$value && !is_numeric(\$value) ? strtotime(\$value) : \$value;
Karson authored
866 867
EOD;
        }
Karson authored
868 869 870 871 872 873
        else if (in_array($inputType, ['checkbox', 'select']))
        {
            $return = <<<EOD
return is_array(\$value) ? implode(',', \$value) : \$value;
EOD;
        }
Karson authored
874
        $setAttr[] = <<<EOD
875
    protected function set{$attrField}Attr(\$value)
Karson authored
876 877 878 879 880 881 882 883 884 885 886 887 888
    {
        $return
    }
EOD;
    }

    protected function appendAttr(&$appendAttrList, $field)
    {
        $appendAttrList[] = <<<EOD
        '{$field}_text'
EOD;
    }
889 890 891 892 893 894
    protected function getModelName($model, $table)
    {
        if (!$model)
        {
            $modelarr = explode('_', strtolower($table));
            foreach ($modelarr as $k => &$v)
895
                $v = ucfirst($v);
896 897 898 899 900
            unset($v);
            $modelName = implode('', $modelarr);
        }
        else
        {
901
            $modelName = ucfirst($model);
902 903 904 905
        }
        return $modelName;
    }
Karson authored
906 907 908 909 910 911 912 913 914
    /**
     * 写入到文件
     * @param string $name
     * @param array $data
     * @param string $pathname
     * @return mixed
     */
    protected function writeToFile($name, $data, $pathname)
    {
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
        $content = $this->getReplacedStub($name, $data);

        if (!is_dir(dirname($pathname)))
        {
            mkdir(strtolower(dirname($pathname)), 0755, true);
        }
        return file_put_contents($pathname, $content);
    }

    /**
     * 获取替换后的数据
     * @param string $name
     * @param array $data
     * @return string
     */
    protected function getReplacedStub($name, $data)
    {
Karson authored
932 933 934 935 936 937
        $search = $replace = [];
        foreach ($data as $k => $v)
        {
            $search[] = "{%{$k}%}";
            $replace[] = $v;
        }
938 939 940 941 942 943 944 945 946
        $stubname = $this->getStub($name);
        if (isset($this->stubList[$stubname]))
        {
            $stub = $this->stubList[$stubname];
        }
        else
        {
            $this->stubList[$stubname] = $stub = file_get_contents($stubname);
        }
Karson authored
947
        $content = str_replace($search, $replace, $stub);
948
        return $content;
Karson authored
949 950 951 952 953 954 955 956 957
    }

    /**
     * 获取基础模板
     * @param string $name
     * @return string
     */
    protected function getStub($name)
    {
958
        return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
Karson authored
959 960 961 962
    }

    protected function getLangItem($field, $content)
    {
963
        if ($content || !Lang::has($field))
Karson authored
964
        {
965
            $itemArr = [];
966
            $content = str_replace(',', ',', $content);
967 968 969 970 971 972
            if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false)
            {
                list($fieldLang, $item) = explode(':', $content);
                $itemArr = [$field => $fieldLang];
                foreach (explode(',', $item) as $k => $v)
                {
973 974 975 976 977 978
                    $valArr = explode('=', $v);
                    if (count($valArr) == 2)
                    {
                        list($key, $value) = $valArr;
                        $itemArr[$field . ' ' . $key] = $value;
                    }
979 980 981 982 983 984 985 986 987
                }
            }
            else
            {
                $itemArr = [$field => $content];
            }
            $resultArr = [];
            foreach ($itemArr as $k => $v)
            {
988
                $resultArr[] = "    '" . mb_ucfirst($k) . "'  =>  '{$v}'";
989 990
            }
            return implode(",\n", $resultArr);
Karson authored
991 992 993 994 995 996 997 998
        }
        else
        {
            return '';
        }
    }

    /**
999 1000
     * 读取数据和语言数组列表
     * @param array $arr
1001
     * @param boolean $withTpl
1002 1003 1004 1005 1006 1007 1008
     * @return array
     */
    protected function getLangArray($arr, $withTpl = TRUE)
    {
        $langArr = [];
        foreach ($arr as $k => $v)
        {
1009
            $langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
        }
        return $langArr;
    }

    /**
     * 将数据转换成带字符串
     * @param array $arr
     * @return string
     */
    protected function getArrayString($arr)
    {
1021 1022
        if (!is_array($arr))
            return $arr;
1023 1024 1025 1026 1027 1028 1029 1030 1031
        $stringArr = [];
        foreach ($arr as $k => $v)
        {
            $is_var = in_array(substr($v, 0, 1), ['$', '_']);
            if (!$is_var)
            {
                $v = str_replace("'", "\'", $v);
                $k = str_replace("'", "\'", $k);
            }
1032
            $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
1033 1034 1035 1036
        }
        return implode(",", $stringArr);
    }
1037 1038 1039
    protected function getItemArray($item, $field, $comment)
    {
        $itemArr = [];
1040
        $comment = str_replace('', ',', $comment);
1041 1042 1043 1044 1045 1046
        if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false)
        {
            list($fieldLang, $item) = explode(':', $comment);
            $itemArr = [];
            foreach (explode(',', $item) as $k => $v)
            {
1047 1048 1049 1050 1051 1052
                $valArr = explode('=', $v);
                if (count($valArr) == 2)
                {
                    list($key, $value) = $valArr;
                    $itemArr[$key] = $field . ' ' . $key;
                }
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
            }
        }
        else
        {
            foreach ($item as $k => $v)
            {
                $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
            }
        }
        return $itemArr;
    }
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
    protected function getFieldType(& $v)
    {
        $inputType = 'text';
        switch ($v['DATA_TYPE'])
        {
            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;
            case 'year';
            case 'date';
            case 'time';
            case 'datetime';
            case 'timestamp';
                $inputType = 'datetime';
                break;
            default:
                break;
        }
        $fieldsName = $v['COLUMN_NAME'];
Karson authored
1104
        // 指定后缀说明也是个时间字段
1105
        if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix))
1106 1107 1108
        {
            $inputType = 'datetime';
        }
Karson authored
1109
        // 指定后缀结尾且类型为enum,说明是个单选框
1110
        if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum')
1111 1112 1113
        {
            $inputType = "radio";
        }
Karson authored
1114
        // 指定后缀结尾且类型为set,说明是个复选框
1115
        if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set')
1116 1117 1118
        {
            $inputType = "checkbox";
        }
Karson authored
1119
        // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
1120
        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
1121 1122 1123
        {
            $inputType = "switch";
        }
Karson authored
1124 1125 1126 1127 1128
        // 指定后缀结尾城市选择框
        if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char'))
        {
            $inputType = "citypicker";
        }
1129 1130 1131 1132
        return $inputType;
    }

    /**
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
     * 判断是否符合指定后缀
     * @param string $field 字段名称
     * @param mixed $suffixArr 后缀
     * @return boolean
     */
    protected function isMatchSuffix($field, $suffixArr)
    {
        $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
        foreach ($suffixArr as $k => $v)
        {
            if (preg_match("/{$v}$/i", $field))
            {
                return true;
            }
        }
        return false;
    }

    /**
Karson authored
1152 1153 1154 1155 1156 1157 1158
     * 获取表单分组数据
     * @param string $field
     * @param string $content
     * @return string
     */
    protected function getFormGroup($field, $content)
    {
1159
        $langField = mb_ucfirst($field);
Karson authored
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
        return<<<EOD
    <div class="form-group">
        <label for="c-{$field}" class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
        <div class="col-xs-12 col-sm-8">
            {$content}
        </div>
    </div>
EOD;
    }

    /**
     * 获取图片模板数据
     * @param string $field
     * @param string $content
     * @return array
     */
    protected function getImageUpload($field, $content)
    {
Karson authored
1178
        $uploadfilter = $selectfilter = '';
1179
        if ($this->isMatchSuffix($field, $this->imageField))
Karson authored
1180
        {
Karson authored
1181 1182
            $uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"';
            $selectfilter = ' data-mimetype="image/*"';
Karson authored
1183
        }
1184
        $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
Karson authored
1185
        $preview = $uploadfilter ? ' data-preview-id="p-' . $field . '"' : '';
1186
        $previewcontainer = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $field . '"></ul>' : '';
Karson authored
1187
        return <<<EOD
1188
<div class="input-group">
Karson authored
1189
                {$content}
1190 1191 1192 1193
                <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>
1194
                <span class="msg-box n-right" for="c-{$field}"></span>
Karson authored
1195
            </div>
1196
            {$previewcontainer}
Karson authored
1197 1198 1199 1200 1201 1202
EOD;
    }

    /**
     * 获取JS列数据
     * @param string $field
1203 1204 1205
     * @param string $datatype
     * @param string $extend
     * @param array $itemArr
Karson authored
1206 1207
     * @return string
     */
1208
    protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = [])
Karson authored
1209
    {
1210
        $lang = mb_ucfirst($field);
Karson authored
1211
        $formatter = '';
Karson authored
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
        foreach ($this->fieldFormatterSuffix as $k => $v)
        {
            if (preg_match("/{$k}$/i", $field))
            {
                if (is_array($v))
                {
                    if (in_array($datatype, $v['type']))
                    {
                        $formatter = $v['name'];
                        break;
                    }
                }
                else
                {
                    $formatter = $v;
                    break;
                }
            }
        }
1231 1232 1233 1234 1235 1236
        if ($formatter)
        {
            $extend = '';
        }
        $html = str_repeat(" ", 24) . "{field: '{$field}{$extend}', title: __('{$lang}')";
        //$formatter = $extend ? '' : $formatter;
1237
        if ($extend)
1238
        {
1239
            $html .= ", operate:false";
1240 1241 1242 1243 1244
            if ($datatype == 'set')
            {
                $formatter = 'label';
            }
        }
1245 1246 1247 1248 1249 1250
        foreach ($itemArr as $k => &$v)
        {
            if (substr($v, 0, 3) !== '__(')
                $v = "__('" . $v . "')";
        }
        unset($v);
1251
        $searchList = json_encode($itemArr, JSON_FORCE_OBJECT);
1252 1253 1254 1255 1256 1257 1258 1259 1260
        $searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList);
        if ($itemArr && !$extend)
        {
            $html .= ", searchList: " . $searchList;
        }
        if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime')
        {
            $html .= ", operate:'RANGE', addclass:'datetimerange'";
        }
1261
        else if (in_array($datatype, ['float', 'double', 'decimal']))
1262 1263 1264
        {
            $html .= ", operate:'BETWEEN'";
        }
1265
        if ($formatter)
Karson authored
1266 1267 1268
            $html .= ", formatter: Table.api.formatter." . $formatter . "}";
        else
            $html .= "}";
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
        if ($extend)
        {
            $origin = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}'), visible:false";
            if ($searchList)
            {
                $origin .= ", searchList: " . $searchList;
            }
            $origin .= "}";
            $html = $origin . ",\n" . $html;
        }
Karson authored
1279 1280 1281
        return $html;
    }
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    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
1293
}