['user_id', 'user_ids', 'admin_id', 'admin_ids'] ]; /** * Enum类型识别为单选框的结尾字符,默认会识别为单选下拉列表 */ protected $enumRadioSuffix = ['data', 'state', 'status']; /** * Set类型识别为复选框的结尾字符,默认会识别为多选下拉列表 */ protected $setCheckboxSuffix = ['data', 'state', 'status']; /** * Int类型识别为日期时间的结尾字符,默认会识别为日期文本框 */ protected $intDateSuffix = ['time']; /** * 开关后缀 */ protected $switchSuffix = ['switch']; /** * 城市后缀 */ protected $citySuffix = ['city']; /** * Selectpage对应的后缀 */ protected $selectpageSuffix = ['_id', '_ids']; /** * Selectpage多选对应的后缀 */ protected $selectpagesSuffix = ['_ids']; /** * 以指定字符结尾的字段格式化函数 */ protected $fieldFormatterSuffix = [ 'status' => ['type' => ['varchar'], 'name' => 'status'], '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']; /** * 保留字段 */ protected $reservedField = ['admin_id', 'createtime', 'updatetime']; /** * 排除字段 */ protected $ignoreFields = []; /** * 排序字段 */ protected $sortField = 'weigh'; /** * 编辑器的Class */ protected $editorClass = 'editor'; 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) ->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) ->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) ->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) ->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) ->addOption('editorclass', null, Option::VALUE_OPTIONAL, 'automatically generate editor class', null) ->setDescription('Build CRUD controller and model from table'); } protected function execute(Input $input, Output $output) { $adminPath = dirname(__DIR__) . DS; //表名 $table = $input->getOption('table') ?: ''; //自定义控制器 $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) { throw new Exception('table name can\'t empty'); } //是否生成菜单 $menu = $input->getOption("menu"); //关联表 $relation = $input->getOption('relation'); //自定义关联表模型 $relationModel = $input->getOption('relationmodel'); //模式 $mode = $input->getOption('mode'); //外键 $relationForeignKey = $input->getOption('relationforeignkey'); //主键 $relationPrimaryKey = $input->getOption('relationprimarykey'); //复选框后缀 $setcheckboxsuffix = $input->getOption('setcheckboxsuffix'); //单选框后缀 $enumradiosuffix = $input->getOption('enumradiosuffix'); //图片后缀 $imagefield = $input->getOption('imagefield'); //文件后缀 $filefield = $input->getOption('filefield'); //日期后缀 $intdatesuffix = $input->getOption('intdatesuffix'); //开关后缀 $switchsuffix = $input->getOption('switchsuffix'); //城市后缀 $citysuffix = $input->getOption('citysuffix'); //selectpage后缀 $selectpagesuffix = $input->getOption('selectpagesuffix'); //selectpage多选后缀 $selectpagessuffix = $input->getOption('selectpagessuffix'); //排除字段 $ignoreFields = $input->getOption('ignorefields'); //排序字段 $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; if ($citysuffix) $this->citySuffix = $citysuffix; if ($selectpagesuffix) $this->selectpageSuffix = $selectpagesuffix; if ($selectpagessuffix) $this->selectpagesSuffix = $selectpagessuffix; if ($ignoreFields) $this->ignoreFields = $ignoreFields; if ($editorclass) $this->editorClass = $editorclass; if ($sortfield) $this->sortField = $sortfield; //如果有启用关联模式 if ($relation && !in_array($mode, ['hasone', 'belongsto'])) { throw new Exception("relation table only work in hasone or belongsto mode"); } $dbname = Config::get('database.database'); $prefix = Config::get('database.prefix'); //检查主表 $table = stripos($table, $prefix) === 0 ? substr($table, strlen($prefix)) : $table; $modelTableName = $tableName = $table; $modelTableType = 'table'; $tableInfo = Db::query("SHOW TABLE STATUS LIKE '{$tableName}'", [], TRUE); if (!$tableInfo) { $tableName = $prefix . $table; $modelTableType = 'name'; $tableInfo = Db::query("SHOW TABLE STATUS LIKE '{$tableName}'", [], TRUE); if (!$tableInfo) { throw new Exception("table not found"); } } $tableInfo = $tableInfo[0]; $relationModelTableName = $relationTableName = $relation; $relationModelTableType = 'table'; //检查关联表 if ($relation) { $relation = stripos($relation, $prefix) === 0 ? substr($relation, strlen($prefix)) : $relation; $relationModelTableName = $relationTableName = $relation; $relationTableInfo = Db::query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], TRUE); if (!$relationTableInfo) { $relationTableName = $prefix . $relation; $relationModelTableType = 'name'; $relationTableInfo = Db::query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], TRUE); if (!$relationTableInfo) { throw new Exception("relation table not found"); } } } //根据表名匹配对应的Fontawesome图标 $iconPath = ROOT_PATH . str_replace('/', DS, '/public/assets/libs/font-awesome/less/variables.less'); $iconName = is_file($iconPath) && stripos(file_get_contents($iconPath), '@fa-var-' . $table . ':') ? 'fa fa-' . $table : 'fa fa-circle-o'; //控制器默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入controller,格式为目录层级 $controller = str_replace('_', '', $controller); $controllerArr = !$controller ? explode('_', strtolower($table)) : explode('/', strtolower($controller)); $controllerUrl = implode('/', $controllerArr); $controllerName = ucfirst(array_pop($controllerArr)); $controllerDir = implode(DS, $controllerArr); $controllerFile = ($controllerDir ? $controllerDir . DS : '') . $controllerName . '.php'; $viewDir = $adminPath . 'view' . DS . $controllerUrl . DS; //最终将生成的文件路径 $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'; //模型默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入model,不支持目录层级 $modelName = $this->getModelName($model, $table); $modelFile = ($local ? $adminPath : APP_PATH . 'common' . DS) . 'model' . DS . $modelName . '.php'; $validateFile = $adminPath . 'validate' . DS . $modelName . '.php'; //关联模型默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入relationmodel,不支持目录层级 $relationModelName = $this->getModelName($relationModel, $relation); $relationModelFile = ($local ? $adminPath : APP_PATH . 'common' . DS) . 'model' . DS . $relationModelName . '.php'; //是否为删除模式 $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) { if (file_exists($v)) unlink($v); } $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 "); } //非覆盖模式时如果存在模型文件则报错 if (is_file($modelFile) && !$force) { 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 "); } require $adminPath . 'common.php'; //从数据库中获取表字段信息 $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]); } $fieldArr = []; foreach ($columnList as $k => $v) { $fieldArr[] = $v['COLUMN_NAME']; } $relationFieldArr = []; foreach ($relationColumnList as $k => $v) { $relationFieldArr[] = $v['COLUMN_NAME']; } $addList = []; $editList = []; $javascriptList = []; $langList = []; $field = 'id'; $order = 'id'; $priDefined = FALSE; $priKey = ''; $relationPriKey = ''; foreach ($columnList as $k => $v) { if ($v['COLUMN_KEY'] == 'PRI') { $priKey = $v['COLUMN_NAME']; break; } } if (!$priKey) { throw new Exception('Primary key not found!'); } 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); } } } try { Form::setEscapeHtml(false); $setAttrArr = []; $getAttrArr = []; $getEnumArr = []; $appendAttrList = []; $controllerAssignList = []; //循环所有字段,开始构造视图的HTML和JS信息 foreach ($columnList as $k => $v) { $field = $v['COLUMN_NAME']; $itemArr = []; // 这里构建Enum和Set类型的列表数据 if (in_array($v['DATA_TYPE'], ['enum', 'set'])) { $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1); $itemArr = explode(',', str_replace("'", '', $itemArr)); $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']); } // 语言列表 if ($v['COLUMN_COMMENT'] != '') { $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']); } $inputType = ''; //createtime和updatetime是保留字段不能修改和添加 if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $this->reservedField) && !in_array($field, $this->ignoreFields)) { $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}}"; // 如果默认值非null,则是一个必选项 if ($v['IS_NULLABLE'] == 'NO') { $attrArr['data-rule'] = 'required'; } if ($inputType == 'select') { $cssClassArr[] = 'selectpicker'; $attrArr['class'] = implode(' ', $cssClassArr); if ($v['DATA_TYPE'] == 'set') { $attrArr['multiple'] = ''; $fieldName .= "[]"; } $attrArr['name'] = $fieldName; $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select'); $itemArr = $this->getLangArray($itemArr, FALSE); //添加一个获取器 $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select'); if ($v['DATA_TYPE'] == 'set') { $this->setAttr($setAttrArr, $field, $inputType); } $this->appendAttr($appendAttrList, $field); $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}"]); } else if ($inputType == 'datetime') { $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'; $this->getAttr($getAttrArr, $field, $inputType); $this->setAttr($setAttrArr, $field, $inputType); $this->appendAttr($appendAttrList, $field); 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); } else if ($inputType == 'checkbox' || $inputType == 'radio') { unset($attrArr['data-rule']); $fieldName = $inputType == 'checkbox' ? $fieldName .= "[]" : $fieldName; $attrArr['name'] = "row[{$fieldName}]"; $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $inputType); $itemArr = $this->getLangArray($itemArr, FALSE); //添加一个获取器 $this->getAttr($getAttrArr, $field, $inputType); if ($inputType == 'checkbox') { $this->setAttr($setAttrArr, $field, $inputType); } $this->appendAttr($appendAttrList, $field); $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}"]); } else if ($inputType == 'textarea') { $cssClassArr[] = substr($field, -7) == 'content' ? $this->editorClass : ''; $attrArr['class'] = implode(' ', $cssClassArr); $attrArr['rows'] = 5; $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr); $formEditElement = Form::textarea($fieldName, $editValue, $attrArr); } else if ($inputType == 'switch') { unset($attrArr['data-rule']); if ($defaultValue === '1' || $defaultValue === 'Y') { $yes = $defaultValue; $no = $defaultValue === '1' ? '0' : 'N'; } else { $no = $defaultValue; $yes = $defaultValue === '0' ? '1' : 'Y'; } $formAddElement = $formEditElement = Form::hidden($fieldName, $no, array_merge(['checked' => ''], $attrArr)); $attrArr['id'] = $fieldName . "-switch"; $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)); $formEditElement = str_replace('type="checkbox"', 'type="checkbox" {in name="' . "\$row.{$field}" . '" value="' . $yes . '"}checked{/in}', $formEditElement); } else if ($inputType == 'citypicker') { $attrArr['class'] = implode(' ', $cssClassArr); $attrArr['data-toggle'] = "city-picker"; $formAddElement = sprintf("