| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- <?php
- namespace console\controllers;
- use common\components\dirUtil;
- use Yii;
- use yii\console\Controller;
- class TableSchemaController extends Controller
- {
-
- //生成数据库字典表 ssh
- //执行 ./yii table-schema/create all 生成table.md文件到根目录的doc目录下
- //使用谷歌浏览器打开即可
- public function actionCreate()
- {
- global $argv;
-
- if (!$argv[2] || strcasecmp($argv[2], 'help') === 0) {
- echo "Usage: ./yii table-schema/create [all|tablename] [filename]\n";
- exit;
- }
-
- $db = Yii::$app->db;
- $allTables = $db->getSchema()->getTableNames();
-
- if ('all' === $argv[2]) {
- $tables = array_diff($allTables, $this->filterTables());
- } else {
- if (!in_array($argv[2], $allTables)) {
- echo sprintf("%s isn't exist \n", $argv[2]);
- exit;
- }
- $tables = (array)$argv[2];
- }
- // 当前数据库没有表
- if (count(array_filter($tables)) == 0) {
- echo "Database has not table \n";
- }
- $filePath = dirUtil::getRootDir() . '/doc/table.md';
- $fp = fopen($filePath, 'a+');
- if (!$fp) {
- echo "Open file failed \n";
- }
-
- foreach ($tables as $table) {
- $schema = $db->getTableSchema($table, true);
- if (!$schema->columns) {
- continue;
- }
-
- fwrite($fp, "#### $schema->name 表 \n");
-
- // 表头
- $header = "| 字段名 | 类型 | 说明 | \n";
- $header .= "|:--------:|:---------:|:-------:| \n";
- fwrite($fp, $header);
-
- // 字段
- $row = '';
-
- foreach ($schema->columns as $col => $obj) {
- $comment = $obj->isPrimaryKey ? '主键' : $obj->comment;
- $row .= "| $obj->name | $obj->dbType | $comment | \n";
- }
-
- fwrite($fp, $row);
- fwrite($fp, "\r\n\r\n");
-
- echo "$schema->name successfully \n";
- }
-
- fclose($fp);
- }
-
- /**
- * 需要过滤的表(不希望生成文档的表)
- * @return array
- */
- protected function filterTables()
- {
- $filterTables = [
- 'tbmigration',
- 'tbAuthAssignment',
- 'tbAuthItemChild',
- 'tbAuthRule',
- 'tbItemTable'
- ];
-
- return $filterTables;
- }
-
- /**
- * 所有表
- * @return \string[]
- */
- protected function allTables()
- {
- return Yii::$app->db->getSchema()->getTableNames();
- }
-
- /**
- * 清空
- */
- public function actionClear()
- {
- global $argv;
-
- if (!$argv[2] || strcasecmp($argv[2], 'help') === 0) {
- echo "Usage: ./yii table-schema/clear [filename]\n";
- exit;
- }
- $filePath = dirUtil::getRootDir() . '/doc/table.md';
- if (!is_file($filePath)) {
- echo "$filePath isn't exists \n";
- exit;
- }
-
- $fp = fopen($filePath, 'w');
- if (!$fp) {
- echo "Open file failed \n";
- }
-
- fwrite($fp, '');
- fclose($fp);
-
- echo "Clear successfully \n";
- }
- }
|