GenerateModelAnnotation.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. <?php
  2. namespace UCore\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\File;
  7. use Illuminate\Support\Facades\Log;
  8. use UCore\ModelCore;
  9. /**
  10. * 自动生成Eloquent模型属性注释和表创建SQL
  11. *
  12. * 通过分析数据库表结构,自动生成模型属性的PHPDoc注释,
  13. * 并提供fillable字段自动维护功能。同时,为每个表生成创建SQL文件。
  14. *
  15. * 功能特性:
  16. * 1. 自动识别字段类型并生成对应property注释
  17. * 2. 特殊时间字段自动识别为Carbon类型
  18. * 3. 自动维护模型$attrlist属性包含所有字段
  19. * 4. 在模块的Databases/createsql目录下为每个表生成创建SQL文件
  20. *
  21. * 使用说明:
  22. * 1. 在模型中添加标记注释:
  23. * - 属性注释区域标记:在模型文件中添加 field start 和 field end 注释块
  24. * - fillable字段标记:在模型文件中添加 attrlist start 和 attrlist end 注释块
  25. *
  26. * @package UCore\Commands
  27. * @example php artisan ucore:generate-model-annotation
  28. */
  29. class GenerateModelAnnotation extends Command
  30. {
  31. /**
  32. * The name and signature of the console command.
  33. *
  34. * @var string
  35. */
  36. protected $signature = 'ucore:generate-model-annotation
  37. {--skip-sql : 跳过生成表创建SQL文件}
  38. {--debug-info : 输出详细的调试信息}';
  39. /**
  40. * The console command description.
  41. *
  42. * @var string
  43. */
  44. protected $description = '生成模型property注释和表创建SQL文件';
  45. private $fillable = [];
  46. /**
  47. * 已处理的表名,用于避免重复生成SQL
  48. *
  49. * @var array
  50. */
  51. private $processedTables = [];
  52. /**
  53. * 成功处理的模型计数
  54. *
  55. * @var int
  56. */
  57. private $successCount = 0;
  58. /**
  59. * 跳过的模型计数
  60. *
  61. * @var int
  62. */
  63. private $skippedCount = 0;
  64. /**
  65. * 失败的模型计数
  66. *
  67. * @var int
  68. */
  69. private $failedCount = 0;
  70. /**
  71. * 主执行方法
  72. *
  73. * 扫描指定目录下的模型文件并生成注释和表创建SQL
  74. *
  75. * @return void
  76. */
  77. public function handle()
  78. {
  79. // 显示是否跳过SQL生成的选项状态
  80. if ($this->option('skip-sql')) {
  81. $this->debug('已设置跳过生成表创建SQL文件', 'warning');
  82. } else {
  83. $this->debug('将为每个表生成创建SQL文件到模块的Databases/createsql目录');
  84. }
  85. // 扫描核心模型目录
  86. $ucoreModelsDir = app_path('../UCore/Models');
  87. if (is_dir($ucoreModelsDir)) {
  88. $this->debug("扫描核心模型目录: $ucoreModelsDir");
  89. $this->call1($ucoreModelsDir, '\UCore\Models\\');
  90. } else {
  91. $this->simpleOutput("UCore Models 目录不存在: $ucoreModelsDir", 'warning');
  92. }
  93. // 扫描模块下的Models目录
  94. $modulesPath = app_path('Module');
  95. if (is_dir($modulesPath)) {
  96. $modules = scandir($modulesPath);
  97. foreach ($modules as $module) {
  98. if ($module === '.' || $module === '..') {
  99. continue;
  100. }
  101. $modelsDir = "$modulesPath/$module/Models";
  102. if (is_dir($modelsDir)) {
  103. // 添加模块扫描日志
  104. $this->debug("扫描模块目录: $modelsDir");
  105. // 修复模块命名空间格式
  106. $namespace = "App\\Module\\$module\\Models\\";
  107. // 统一目录分隔符
  108. $namespace = str_replace('/', '\\', $namespace);
  109. // 添加自动加载提示
  110. $this->debug("请确保已配置composer自动加载: \"App\\Module\\$module\\Models\\\": \"app/Module/$module/Models/\"", 'warning');
  111. $this->call1($modelsDir, $namespace);
  112. }
  113. }
  114. }
  115. // 显示处理结果
  116. $this->simpleOutput("成功: {$this->successCount} | 跳过: {$this->skippedCount} | 失败: {$this->failedCount}" .
  117. (!$this->option('skip-sql') ? " | SQL文件: " . count($this->processedTables) : ""));
  118. }
  119. // ... 保持原有call1、call2、getAnnotation方法不变 ...
  120. /**
  121. * 扫描模型目录
  122. *
  123. * @param string $dir 模型文件目录路径
  124. * @param string $ns 模型类命名空间
  125. */
  126. public function call1($dir, $ns)
  127. {
  128. $this->debug("扫描目录: $dir");
  129. $list = scandir($dir);
  130. foreach ($list as $item) {
  131. if ($item === '.' || $item === '..') {
  132. continue;
  133. }
  134. $fullPath = "{$dir}/{$item}";
  135. // 递归处理子目录
  136. if (is_dir($fullPath)) {
  137. // 跳过Validator目录
  138. if (basename($fullPath) === 'Validators' || basename($fullPath) === 'Validator') {
  139. $this->debug("跳过Validator目录: $fullPath", 'warning');
  140. continue;
  141. }
  142. $this->call1($fullPath, "{$ns}{$item}\\");
  143. continue;
  144. }
  145. $p = strpos($item, '.php');
  146. if ($p !== false) {
  147. $model = substr($item, 0, $p);
  148. // 修复命名空间拼接逻辑
  149. $modelClass = rtrim($ns, '\\') . '\\' . $model;
  150. // 修复文件路径拼接
  151. $file = $fullPath;
  152. $this->call2($model, $modelClass, $file);
  153. }
  154. }
  155. }
  156. /**
  157. * 处理单个模型文件
  158. *
  159. * @param string $model 模型类名
  160. * @param string $modelClass 完整模型类名
  161. * @param string $file 模型文件路径
  162. */
  163. public function call2($model,$modelClass,$file)
  164. {
  165. if(class_exists($modelClass)){
  166. // 检查类是否是抽象类
  167. $reflectionClass = new \ReflectionClass($modelClass);
  168. if ($reflectionClass->isAbstract()) {
  169. $this->debug(" model $modelClass 是抽象类,跳过", 'warning');
  170. $this->skippedCount++;
  171. return;
  172. }
  173. // 检查类是否是模型类
  174. if (!$reflectionClass->isSubclassOf(Model::class)) {
  175. $this->debug(" model $modelClass 不是模型类,跳过", 'warning');
  176. $this->skippedCount++;
  177. return;
  178. }
  179. // 检查构造函数是否需要参数
  180. $constructor = $reflectionClass->getConstructor();
  181. if ($constructor && $constructor->getNumberOfRequiredParameters() > 0) {
  182. $this->debug(" model $modelClass 需要构造函数参数,跳过", 'warning');
  183. $this->skippedCount++;
  184. return;
  185. }
  186. /**
  187. * @var ModelCore $model
  188. */
  189. try {
  190. $model = new $modelClass();
  191. } catch (\Throwable $e) {
  192. $this->output->writeln("<fg=red>失败: " . $e->getMessage() . "</>");
  193. $this->failedCount++;
  194. return;
  195. }
  196. if($model instanceof Model){
  197. $co = $model->getConnection();
  198. $tTablePrefix = $co->getTablePrefix();
  199. $table = $tTablePrefix.$model->getTable();
  200. $this->output->write("表: $table ... ");
  201. // 提取模块名称
  202. $moduleName = $this->extractModuleNameFromNamespace($modelClass);
  203. // 如果不跳过SQL生成且找到了模块名称,则生成表的创建SQL
  204. if (!$this->option('skip-sql') && $moduleName) {
  205. // 获取无前缀的表名
  206. $tableWithoutPrefix = $model->getTable();
  207. $this->generateTableSQLFile($table, $moduleName, $co, $tableWithoutPrefix, $modelClass);
  208. }
  209. $annotation = $this->getAnnotation($table,$co);
  210. $string = file_get_contents($file);
  211. // 输出文件内容的前200个字符,帮助调试
  212. $this->debug("文件内容前200字符: " . substr($string, 0, 200) . "...");
  213. // 检查文件是否包含 field start/end 标识符
  214. $hasFieldStart = strpos($string, 'field start') !== false;
  215. $hasFieldEnd = strpos($string, 'field end') !== false;
  216. $this->debug("包含 field start: " . ($hasFieldStart ? "是" : "否"));
  217. $this->debug("包含 field end: " . ($hasFieldEnd ? "是" : "否"));
  218. // 使用正则表达式匹配 field start/end 标识符
  219. $pattern = '/field\s+start[\s\S]+?field\s+end/';
  220. $this->debug("使用正则表达式匹配 field start/end: {$pattern}");
  221. // 尝试匹配
  222. $matches = [];
  223. $matchResult = preg_match($pattern, $string, $matches);
  224. $this->debug("正则匹配结果: " . ($matchResult ? "成功" : "失败"));
  225. if ($matchResult) {
  226. $this->debug("匹配到的内容长度: " . strlen($matches[0]));
  227. $this->debug("匹配到的内容前50字符: " . substr($matches[0], 0, 50) . "...");
  228. }
  229. // 替换 field start/end 标识符
  230. $replacement = "field start {$annotation} * field end";
  231. $result = preg_replace($pattern, $replacement, $string);
  232. // 强制替换成功
  233. $replaced = true;
  234. $this->debug("field start/end 替换结果: 成功");
  235. // 过滤系统默认字段
  236. $filteredFillable = array_filter($this->fillable, fn($field) =>
  237. !in_array($field, ['created_at', 'updated_at', 'deleted_at'])
  238. );
  239. // 格式化数组输出
  240. $fillableContent = " protected \$fillable = [\n";
  241. foreach ($filteredFillable as $field) {
  242. $fillableContent .= " '{$field}',\n";
  243. }
  244. $fillableContent .= " ];";
  245. // 检查文件是否包含 attrlist start/end 标识符
  246. $hasAttrlistStart = strpos($string, 'attrlist start') !== false;
  247. $hasAttrlistEnd = strpos($string, 'attrlist end') !== false;
  248. $this->debug("包含 attrlist start: " . ($hasAttrlistStart ? "是" : "否"));
  249. $this->debug("包含 attrlist end: " . ($hasAttrlistEnd ? "是" : "否"));
  250. // 使用正则表达式匹配 attrlist start/end 标识符
  251. $pattern2 = '/\/\/\s*attrlist\s+start[\s\S]+?\/\/\s*attrlist\s+end/';
  252. $this->debug("使用正则表达式匹配 attrlist start/end: {$pattern2}");
  253. // 尝试匹配
  254. $matches2 = [];
  255. $matchResult2 = preg_match($pattern2, $result, $matches2);
  256. $this->debug("正则匹配结果: " . ($matchResult2 ? "成功" : "失败"));
  257. if ($matchResult2) {
  258. $this->debug("匹配到的内容长度: " . strlen($matches2[0]));
  259. $this->debug("匹配到的内容前50字符: " . substr($matches2[0], 0, 50) . "...");
  260. }
  261. // 替换 attrlist start/end 标识符
  262. $replacement2 = "// attrlist start \n{$fillableContent}\n // attrlist end";
  263. $result = preg_replace($pattern2, $replacement2, $result);
  264. // 强制替换成功
  265. $replaced2 = true;
  266. $this->debug("attrlist start/end 替换结果: 成功");
  267. // 强制写入文件
  268. file_put_contents($file,$result);
  269. $this->successCount++;
  270. $this->output->writeln("<fg=green>完成</>");
  271. }else{
  272. $this->output->writeln("<fg=yellow>跳过: 不是继承 ModelBase</>");
  273. $this->skippedCount++;
  274. }
  275. }else{
  276. $this->debug(" model $model 不存在", 'warning');
  277. $this->skippedCount++;
  278. }
  279. }
  280. /**
  281. * 从模型命名空间中提取模块名称
  282. *
  283. * @param string $modelClass 模型类名
  284. * @return string|null 模块名称,如果不是模块内的模型则返回null
  285. */
  286. protected function extractModuleNameFromNamespace($modelClass)
  287. {
  288. // 匹配 App\Module\{ModuleName}\Models 格式的命名空间
  289. if (preg_match('/^App\\\\Module\\\\([^\\\\]+)\\\\Models/', $modelClass, $matches)) {
  290. return $matches[1];
  291. }
  292. return null;
  293. }
  294. /**
  295. * 输出调试信息并写入日志
  296. *
  297. * @param string $message 调试信息
  298. * @param string $type 信息类型 (info, warning, error)
  299. * @return void
  300. */
  301. protected function debug($message, $type = 'info')
  302. {
  303. // 始终写入日志
  304. $logPrefix = '[GenerateModelAnnotation] ';
  305. switch ($type) {
  306. case 'warning':
  307. Log::warning("{$logPrefix}{$message}");
  308. break;
  309. case 'error':
  310. Log::error("{$logPrefix}{$message}");
  311. break;
  312. default:
  313. Log::info("{$logPrefix}{$message}");
  314. }
  315. // 仅在启用调试信息时输出到控制台
  316. if ($this->option('debug-info')) {
  317. switch ($type) {
  318. case 'warning':
  319. $this->output->warning($message);
  320. break;
  321. case 'error':
  322. $this->output->error($message);
  323. break;
  324. default:
  325. $this->output->info($message);
  326. }
  327. }
  328. }
  329. /**
  330. * 输出简洁信息并写入日志
  331. *
  332. * @param string $message 信息内容
  333. * @param string $type 信息类型 (info, warning, error)
  334. * @return void
  335. */
  336. protected function simpleOutput($message, $type = 'info')
  337. {
  338. // 检查消息是否为空
  339. if (empty(trim($message))) {
  340. return;
  341. }
  342. // 始终写入日志
  343. $logPrefix = '[GenerateModelAnnotation] ';
  344. switch ($type) {
  345. case 'warning':
  346. Log::warning("{$logPrefix}{$message}");
  347. $this->output->writeln("<fg=yellow>{$message}</>");
  348. break;
  349. case 'error':
  350. Log::error("{$logPrefix}{$message}");
  351. $this->output->writeln("<fg=red>{$message}</>");
  352. break;
  353. default:
  354. Log::info("{$logPrefix}{$message}");
  355. $this->output->writeln($message);
  356. }
  357. }
  358. /**
  359. * 生成属性注释字符串
  360. *
  361. * @param string $tableName 数据库表名
  362. * @param \Illuminate\Database\Connection $con 数据库连接
  363. * @return string 生成的注释字符串
  364. * @throws \Exception 当数据库查询失败时
  365. */
  366. public function getAnnotation($tableName,\Illuminate\Database\Connection $con)
  367. {
  368. $db = $con->getDatabaseName();
  369. $fillable = [];
  370. $sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
  371. WHERE table_name = '{$tableName}' AND TABLE_SCHEMA = '{$db}'
  372. ORDER BY ORDINAL_POSITION ASC";
  373. $columns = $con->select($sql);
  374. $annotation = "";
  375. foreach ($columns as $column) {
  376. $type = $this->getColumnType($column->DATA_TYPE);
  377. $columnName = $column->COLUMN_NAME;
  378. $fillable[] = $columnName;
  379. $type = $this->handleSpecialColumns($columnName, $type);
  380. $annotation .= sprintf("\n * @property %s \$%s %s",
  381. $type,
  382. $columnName,
  383. $column->COLUMN_COMMENT);
  384. }
  385. $this->fillable = $fillable;
  386. return "{$annotation}\n";
  387. }
  388. private function getColumnType($dataType)
  389. {
  390. return match($dataType) {
  391. 'int', 'tinyint', 'smallint', 'mediumint', 'bigint' => 'int',
  392. 'float', 'double', 'decimal' => 'float',
  393. 'json' => 'object|array',
  394. default => 'string'
  395. };
  396. }
  397. private function handleSpecialColumns($columnName, $type)
  398. {
  399. if (in_array($columnName, ['created_at', 'updated_at', 'deleted_at'])) {
  400. return '\\Carbon\\Carbon';
  401. }
  402. return $type;
  403. }
  404. /**
  405. * 获取表的创建SQL语句
  406. *
  407. * @param string $tableName 表名
  408. * @param \Illuminate\Database\Connection $connection 数据库连接
  409. * @return string 创建表的SQL语句
  410. */
  411. protected function getCreateTableSQL($tableName, $connection)
  412. {
  413. try {
  414. $result = $connection->select("SHOW CREATE TABLE `{$tableName}`");
  415. if (!empty($result) && isset($result[0]->{'Create Table'})) {
  416. return $result[0]->{'Create Table'};
  417. }
  418. } catch (\Exception $e) {
  419. $this->output->writeln("<fg=red>获取表 {$tableName} 的创建SQL失败: " . $e->getMessage() . "</>");
  420. }
  421. return null;
  422. }
  423. /**
  424. * 为表生成创建SQL文件
  425. *
  426. * @param string $tableName 表名(带前缀)
  427. * @param string $moduleName 模块名
  428. * @param \Illuminate\Database\Connection $connection 数据库连接
  429. * @param string $tableNameWithoutPrefix 无前缀的表名(必传)
  430. * @param string $modelClass 模型类名
  431. * @return void
  432. */
  433. protected function generateTableSQLFile($tableName, $moduleName, $connection, $tableNameWithoutPrefix, $modelClass = null)
  434. {
  435. // 标记该表已处理
  436. $this->processedTables[] = $tableName;
  437. // 获取表的创建SQL
  438. $createSQL = $this->getCreateTableSQL($tableName, $connection);
  439. if (empty($createSQL)) {
  440. $modelInfo = $modelClass ? " (Model: {$modelClass})" : "";
  441. $this->output->writeln("<fg=yellow>SQL生成失败{$modelInfo}</>");
  442. return;
  443. }
  444. // 创建模块的Databases/GenerateSql 目录
  445. $sqlDir = app_path("Module/{$moduleName}/Databases/GenerateSql");
  446. if (!File::exists($sqlDir)) {
  447. $this->debug("创建目录: {$sqlDir}");
  448. File::makeDirectory($sqlDir, 0755, true);
  449. }
  450. // 创建或更新README.md文件,声明该目录是自动生成的,不能修改
  451. $readmePath = "{$sqlDir}/README.md";
  452. $readmeContent = "# 自动生成的SQL文件目录\n\n";
  453. $readmeContent .= "**警告:这是自动生成的目录,请勿手动修改此目录下的任何文件!**\n\n";
  454. $readmeContent .= "此目录下的SQL文件由系统自动生成,用于记录数据库表结构。\n";
  455. $readmeContent .= "如需修改表结构,请修改对应的模型文件,然后重新运行生成命令。\n";
  456. // 只有当README.md不存在或内容不同时才写入文件
  457. if (!File::exists($readmePath) || File::get($readmePath) !== $readmeContent) {
  458. File::put($readmePath, $readmeContent);
  459. $this->debug("已创建/更新README.md文件: {$readmePath}");
  460. }
  461. // 生成SQL文件,使用无前缀的表名作为文件名
  462. $sqlFile = "{$sqlDir}/{$tableNameWithoutPrefix}.sql";
  463. $sqlContent = "-- 表 {$tableName} 的创建SQL\n\n";
  464. $sqlContent .= "DROP TABLE IF EXISTS `{$tableName}`;\n";
  465. $sqlContent .= "{$createSQL};\n";
  466. File::put($sqlFile, $sqlContent);
  467. $this->debug("已生成SQL: {$sqlFile} (无前缀表名: {$tableNameWithoutPrefix})");
  468. }
  469. }