MigrationGenerator.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. declare(strict_types=1);
  3. namespace SixShop\MakerBundle\Generator;
  4. use Symfony\Component\Console\Style\SymfonyStyle;
  5. use Phinx\Util\Util;
  6. class MigrationGenerator
  7. {
  8. private string $migrationsPath;
  9. private array $fieldTypes = [
  10. 'integer' => 'integer',
  11. 'biginteger' => 'bigInteger',
  12. 'string' => 'string',
  13. 'text' => 'text',
  14. 'boolean' => 'boolean',
  15. 'datetime' => 'datetime',
  16. 'timestamp' => 'timestamp',
  17. 'date' => 'date',
  18. 'time' => 'time',
  19. 'decimal' => 'decimal',
  20. 'float' => 'float',
  21. 'binary' => 'binary',
  22. 'json' => 'json'
  23. ];
  24. public function __construct(?string $migrationsPath = null)
  25. {
  26. $this->migrationsPath = $migrationsPath ?: getcwd() . '/database/migrations';
  27. }
  28. /**
  29. * Generate migration file based on table definition
  30. */
  31. public function generateMigration(string $tableName, array $fields = [], string $action = 'create', ?SymfonyStyle $io = null): bool
  32. {
  33. try {
  34. // Ensure migrations directory exists
  35. if (!is_dir($this->migrationsPath)) {
  36. if (!mkdir($this->migrationsPath, 0755, true)) {
  37. if ($io) {
  38. $io->error("无法创建迁移目录: {$this->migrationsPath}");
  39. }
  40. return false;
  41. }
  42. }
  43. // Generate migration name and class name
  44. $migrationName = $this->generateMigrationName($tableName, $action);
  45. $className = $this->generateClassName($migrationName);
  46. // Generate timestamp
  47. $timestamp = date('YmdHis');
  48. $filename = $timestamp . '_' . $migrationName . '.php';
  49. $filePath = $this->migrationsPath . '/' . $filename;
  50. // Generate migration content
  51. $content = $this->generateMigrationContent($className, $tableName, $fields, $action);
  52. // Write migration file
  53. if (file_put_contents($filePath, $content) !== false) {
  54. if ($io) {
  55. $io->success("Migration created: {$filename}");
  56. }
  57. return true;
  58. } else {
  59. if ($io) {
  60. $io->error("无法写入迁移文件: {$filename}");
  61. }
  62. return false;
  63. }
  64. } catch (\Exception $e) {
  65. if ($io) {
  66. $io->error('生成迁移文件时发生错误: ' . $e->getMessage());
  67. }
  68. return false;
  69. }
  70. }
  71. /**
  72. * Generate migration name
  73. */
  74. private function generateMigrationName(string $tableName, string $action): string
  75. {
  76. switch ($action) {
  77. case 'create':
  78. return 'create_' . $tableName . '_table';
  79. case 'add_column':
  80. return 'add_columns_to_' . $tableName . '_table';
  81. case 'drop_column':
  82. return 'drop_columns_from_' . $tableName . '_table';
  83. case 'modify':
  84. return 'modify_' . $tableName . '_table';
  85. default:
  86. return 'update_' . $tableName . '_table';
  87. }
  88. }
  89. /**
  90. * Generate migration class name
  91. */
  92. private function generateClassName(string $migrationName): string
  93. {
  94. return Util::mapFileNameToClassName($migrationName);
  95. }
  96. /**
  97. * Generate migration file content
  98. */
  99. private function generateMigrationContent(string $className, string $tableName, array $fields, string $action): string
  100. {
  101. $content = "<?php\n";
  102. $content .= "declare(strict_types=1);\n\n";
  103. $content .= "use Phinx\\Migration\\AbstractMigration;\n\n";
  104. $content .= "final class {$className} extends AbstractMigration\n";
  105. $content .= "{\n";
  106. // Generate change method
  107. $content .= " /**\n";
  108. $content .= " * Change Method.\n";
  109. $content .= " *\n";
  110. $content .= " * Write your reversible migrations using this method.\n";
  111. $content .= " *\n";
  112. $content .= " * More information on writing migrations is available here:\n";
  113. $content .= " * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method\n";
  114. $content .= " *\n";
  115. $content .= " * Remember to call \"create()\" or \"update()\" and NOT \"save()\" when working\n";
  116. $content .= " * with the Table class.\n";
  117. $content .= " */\n";
  118. $content .= " public function change(): void\n";
  119. $content .= " {\n";
  120. switch ($action) {
  121. case 'create':
  122. $content .= $this->generateCreateTableContent($tableName, $fields);
  123. break;
  124. case 'add_column':
  125. $content .= $this->generateAddColumnContent($tableName, $fields);
  126. break;
  127. case 'drop_column':
  128. $content .= $this->generateDropColumnContent($tableName, $fields);
  129. break;
  130. default:
  131. $content .= $this->generateModifyTableContent($tableName, $fields);
  132. break;
  133. }
  134. $content .= " }\n";
  135. $content .= "}\n";
  136. return $content;
  137. }
  138. /**
  139. * Generate create table content
  140. */
  141. private function generateCreateTableContent(string $tableName, array $fields): string
  142. {
  143. $content = " \$table = \$this->table('{$tableName}');\n";
  144. if (!empty($fields)) {
  145. foreach ($fields as $field) {
  146. $fieldName = $field['name'];
  147. $fieldType = $this->fieldTypes[$field['type']] ?? 'string';
  148. $options = $this->buildFieldOptions($field);
  149. $content .= " \$table->addColumn('{$fieldName}', '{$fieldType}'";
  150. if (!empty($options)) {
  151. $content .= ", " . $this->arrayToString($options);
  152. }
  153. $content .= ");\n";
  154. }
  155. }
  156. // Add indexes if specified
  157. foreach ($fields as $field) {
  158. if (!empty($field['index'])) {
  159. $content .= " \$table->addIndex(['{$field['name']}']);\n";
  160. }
  161. if (!empty($field['unique'])) {
  162. $content .= " \$table->addIndex(['{$field['name']}'], ['unique' => true]);\n";
  163. }
  164. }
  165. $content .= " \$table->create();\n";
  166. return $content;
  167. }
  168. /**
  169. * Generate add column content
  170. */
  171. private function generateAddColumnContent(string $tableName, array $fields): string
  172. {
  173. $content = " \$table = \$this->table('{$tableName}');\n";
  174. foreach ($fields as $field) {
  175. $fieldName = $field['name'];
  176. $fieldType = $this->fieldTypes[$field['type']] ?? 'string';
  177. $options = $this->buildFieldOptions($field);
  178. $content .= " \$table->addColumn('{$fieldName}', '{$fieldType}'";
  179. if (!empty($options)) {
  180. $content .= ", " . $this->arrayToString($options);
  181. }
  182. $content .= ");\n";
  183. }
  184. $content .= " \$table->update();\n";
  185. return $content;
  186. }
  187. /**
  188. * Generate drop column content
  189. */
  190. private function generateDropColumnContent(string $tableName, array $fields): string
  191. {
  192. $content = " \$table = \$this->table('{$tableName}');\n";
  193. foreach ($fields as $field) {
  194. $fieldName = is_array($field) ? $field['name'] : $field;
  195. $content .= " \$table->removeColumn('{$fieldName}');\n";
  196. }
  197. $content .= " \$table->update();\n";
  198. return $content;
  199. }
  200. /**
  201. * Generate modify table content
  202. */
  203. private function generateModifyTableContent(string $tableName, array $fields): string
  204. {
  205. $content = " \$table = \$this->table('{$tableName}');\n";
  206. $content .= " // Add your table modifications here\n";
  207. $content .= " \$table->update();\n";
  208. return $content;
  209. }
  210. /**
  211. * Build field options array
  212. */
  213. private function buildFieldOptions(array $field): array
  214. {
  215. $options = [];
  216. if (isset($field['length'])) {
  217. $options['limit'] = (int)$field['length'];
  218. }
  219. if (isset($field['null'])) {
  220. $options['null'] = (bool)$field['null'];
  221. } else {
  222. $options['null'] = true; // Default to nullable
  223. }
  224. if (isset($field['default'])) {
  225. $options['default'] = $field['default'];
  226. }
  227. if (isset($field['comment'])) {
  228. $options['comment'] = $field['comment'];
  229. }
  230. if (isset($field['after'])) {
  231. $options['after'] = $field['after'];
  232. }
  233. // Handle precision and scale for decimal fields
  234. if ($field['type'] === 'decimal') {
  235. if (isset($field['precision'])) {
  236. $options['precision'] = (int)$field['precision'];
  237. }
  238. if (isset($field['scale'])) {
  239. $options['scale'] = (int)$field['scale'];
  240. }
  241. }
  242. return $options;
  243. }
  244. /**
  245. * Convert array to string representation
  246. */
  247. private function arrayToString(array $array): string
  248. {
  249. $parts = [];
  250. foreach ($array as $key => $value) {
  251. if (is_string($value)) {
  252. $parts[] = "'{$key}' => '{$value}'";
  253. } elseif (is_bool($value)) {
  254. $parts[] = "'{$key}' => " . ($value ? 'true' : 'false');
  255. } elseif (is_null($value)) {
  256. $parts[] = "'{$key}' => null";
  257. } else {
  258. $parts[] = "'{$key}' => {$value}";
  259. }
  260. }
  261. return '[' . implode(', ', $parts) . ']';
  262. }
  263. /**
  264. * Get supported field types
  265. */
  266. public function getSupportedFieldTypes(): array
  267. {
  268. return array_keys($this->fieldTypes);
  269. }
  270. /**
  271. * Set migrations path
  272. */
  273. public function setMigrationsPath(string $path): void
  274. {
  275. $this->migrationsPath = $path;
  276. }
  277. /**
  278. * Get migrations path
  279. */
  280. public function getMigrationsPath(): string
  281. {
  282. return $this->migrationsPath;
  283. }
  284. }