GenerateModelAnnotation.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 UCore\ModelCore;
  7. /**
  8. * 自动生成Eloquent模型属性注释
  9. *
  10. * 通过分析数据库表结构,自动生成模型属性的PHPDoc注释,
  11. * 并提供fillable字段自动维护功能。
  12. *
  13. * 功能特性:
  14. * 1. 自动识别字段类型并生成对应@property注释
  15. * 2. 特殊时间字段自动识别为Carbon类型
  16. * 3. 自动维护模型$attrlist属性包含所有字段
  17. *
  18. * 使用说明:
  19. * 1. 在模型中添加标记注释:
  20. * - 属性注释区域标记:在模型文件中添加 field start 和 field end 注释块
  21. * - fillable字段标记:在模型文件中添加 attrlist start 和 attrlist end 注释块
  22. *
  23. * @package UCore\Commands
  24. * @example php artisan ucore:generate-model-annotation
  25. */
  26. class GenerateModelAnnotation extends Command
  27. {
  28. /**
  29. * The name and signature of the console command.
  30. *
  31. * @var string
  32. */
  33. protected $signature = 'ucore:generate-model-annotation';
  34. /**
  35. * The console command description.
  36. *
  37. * @var string
  38. */
  39. protected $description = '生成模型property注释,使得IDE有模型属性提示!';
  40. private $fillable = [];
  41. /**
  42. * 主执行方法
  43. *
  44. * 扫描指定目录下的模型文件并生成注释
  45. *
  46. * @return void
  47. */
  48. public function handle()
  49. {
  50. // 扫描核心模型目录
  51. $this->call1(app_path('../ucore'), '\App\Models\\');
  52. // 扫描模块下的Models目录
  53. $modulesPath = app_path('Module');
  54. if (is_dir($modulesPath)) {
  55. $modules = scandir($modulesPath);
  56. foreach ($modules as $module) {
  57. if ($module === '.' || $module === '..') {
  58. continue;
  59. }
  60. $modelsDir = "$modulesPath/$module/Models";
  61. if (is_dir($modelsDir)) {
  62. // 添加模块扫描日志
  63. $this->info("扫描模块目录: $modelsDir");
  64. // 修复模块命名空间格式
  65. $namespace = "App\\Module\\$module\\Models\\";
  66. // 统一目录分隔符
  67. $namespace = str_replace('/', '\\', $namespace);
  68. // 添加自动加载提示
  69. $this->warn("请确保已配置composer自动加载: \"App\\Module\\$module\\Models\\\": \"app/Module/$module/Models/\"");
  70. $this->call1($modelsDir, $namespace);
  71. }
  72. }
  73. }
  74. }
  75. // ... 保持原有call1、call2、getAnnotation方法不变 ...
  76. /**
  77. * 扫描模型目录
  78. *
  79. * @param string $dir 模型文件目录路径
  80. * @param string $ns 模型类命名空间
  81. */
  82. public function call1($dir, $ns)
  83. {
  84. $this->info("扫描目录: $dir");
  85. $list = scandir($dir);
  86. foreach ($list as $item) {
  87. if ($item === '.' || $item === '..') {
  88. continue;
  89. }
  90. $fullPath = $dir . '/' . $item;
  91. // 递归处理子目录
  92. if (is_dir($fullPath)) {
  93. $this->call1($fullPath, $ns . $item . '\\');
  94. continue;
  95. }
  96. $p = strpos($item, '.php');
  97. if ($p !== false) {
  98. $model = substr($item, 0, $p);
  99. // 修复命名空间拼接逻辑
  100. $modelClass = rtrim($ns, '\\') . '\\' . $model;
  101. // 修复文件路径拼接
  102. $file = $fullPath;
  103. $this->call2($model, $modelClass, $file);
  104. }
  105. }
  106. }
  107. /**
  108. * 处理单个模型文件
  109. *
  110. * @param string $model 模型类名
  111. * @param string $modelClass 完整模型类名
  112. * @param string $file 模型文件路径
  113. */
  114. public function call2($model,$modelClass,$file)
  115. {
  116. if(class_exists($modelClass)){
  117. /**
  118. * @var ModelCore $model
  119. */
  120. $model = new $modelClass();
  121. if($model instanceof Model){
  122. $co = $model->getConnection();
  123. $tTablePrefix = $co->getTablePrefix();
  124. $table =$tTablePrefix.$model->getTable();
  125. $this->info("table $table ");
  126. $annotation = $this->getAnnotation($table,$co);
  127. $pattern = '/field start[\s\S]+field end/';
  128. $replacement = "field start ".$annotation." * field end";
  129. $string = file_get_contents($file);
  130. $result = preg_replace($pattern, $replacement, $string);
  131. // 过滤系统默认字段
  132. $filteredFillable = array_filter($this->fillable, function($field) {
  133. return !in_array($field, ['created_at', 'updated_at', 'deleted_at']);
  134. });
  135. // 格式化数组输出
  136. $fillableContent = " protected \$fillable = [\n";
  137. foreach ($filteredFillable as $field) {
  138. $fillableContent .= " '{$field}',\n";
  139. }
  140. $fillableContent .= " ];";
  141. $pattern2 = '/attrlist start[\s\S]+attrlist end/';
  142. $replacement2 = "attrlist start \n{$fillableContent}\n // attrlist end";
  143. $result = preg_replace($pattern2, $replacement2, $result);
  144. if($result != $string){
  145. $this->output->info(" model $modelClass file :$file annotation 成功 ");
  146. file_put_contents($file,$result);
  147. }else{
  148. $this->output->warning(" model $modelClass file :$file table $table - 没有标识符 ");
  149. }
  150. }else{
  151. $this->output->warning(" model $modelClass 不是继承 ModelBase");
  152. }
  153. }else{
  154. $this->output->warning(" model $model 不存在");
  155. }
  156. }
  157. /**
  158. * 生成属性注释字符串
  159. *
  160. * @param string $tableName 数据库表名
  161. * @param \Illuminate\Database\Connection $con 数据库连接
  162. * @return string 生成的注释字符串
  163. * @throws \Exception 当数据库查询失败时
  164. */
  165. public function getAnnotation($tableName,\Illuminate\Database\Connection $con)
  166. {
  167. $db = $con->getDatabaseName();
  168. $fillable = [];
  169. $sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
  170. WHERE table_name = '{$tableName}' AND TABLE_SCHEMA = '{$db}'
  171. ORDER BY ORDINAL_POSITION ASC";
  172. $columns = $con->select($sql);
  173. $annotation = "";
  174. foreach ($columns as $column) {
  175. $type = $this->getColumnType($column->DATA_TYPE);
  176. $columnName = $column->COLUMN_NAME;
  177. $fillable[] = $columnName;
  178. $type = $this->handleSpecialColumns($columnName, $type);
  179. $annotation .= sprintf("\n * @property %s \$%s %s",
  180. $type,
  181. $columnName,
  182. $column->COLUMN_COMMENT);
  183. }
  184. $this->fillable = $fillable;
  185. return $annotation."\n";
  186. }
  187. private function getColumnType($dataType)
  188. {
  189. return match($dataType) {
  190. 'int', 'tinyint', 'smallint', 'mediumint', 'bigint' => 'int',
  191. 'float', 'double', 'decimal' => 'float',
  192. 'json' => 'object|array',
  193. default => 'string'
  194. };
  195. }
  196. private function handleSpecialColumns($columnName, $type)
  197. {
  198. if (in_array($columnName, ['created_at', 'updated_at', 'deleted_at'])) {
  199. return '\\Carbon\\Carbon';
  200. }
  201. return $type;
  202. }
  203. }