Migration.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace catcher\generate\factory;
  3. use catcher\CatchAdmin;
  4. use catcher\exceptions\FailedException;
  5. use catcher\Utils;
  6. use JaguarJack\MigrateGenerator\MigrateGenerator;
  7. use think\facade\Db;
  8. use think\helper\Str;
  9. class Migration extends Factory
  10. {
  11. public function done($params)
  12. {
  13. [$module, $tableName] = $params;
  14. // TODO: Implement done() method.
  15. $migrationPath = CatchAdmin::directory() . $module . DIRECTORY_SEPARATOR.
  16. 'database' . DIRECTORY_SEPARATOR . 'migrations' .DIRECTORY_SEPARATOR;
  17. CatchAdmin::makeDirectory($migrationPath);
  18. $migrateGenerator = (new MigrateGenerator('thinkphp'));
  19. $tables = $migrateGenerator->getDatabase()->getAllTables($tableName);
  20. $version = date('YmdHis');
  21. $file = $migrationPath . $version . '_'. $tableName . '.php';
  22. foreach ($tables as $table) {
  23. if ($table->getName() == $tableName) {
  24. $content = $migrateGenerator->getMigrationContent($table);
  25. $noPrefix = str_replace(Utils::tablePrefix(), '', $tableName);
  26. $_content = str_replace($tableName, $noPrefix, $content, $count);
  27. file_put_contents($file, $count == 1 ? $_content : $content);
  28. if (!file_exists($file)) {
  29. throw new FailedException('migration generate failed');
  30. }
  31. $model = new class extends \think\Model {
  32. protected $name = 'migrations';
  33. };
  34. $model->insert([
  35. 'version' => $version,
  36. 'migration_name' => ucfirst(Str::camel($tableName)),
  37. 'start_time' => date('Y-m-d H:i:s'),
  38. 'end_time' => date('Y-m-d H:i:s')
  39. ]);
  40. break;
  41. }
  42. }
  43. return $file;
  44. }
  45. }