Migrate.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. <?php
  2. declare(strict_types=1);
  3. namespace SixShop\System;
  4. use Phinx\Config\Config;
  5. use Phinx\Db\Adapter\AdapterFactory;
  6. use Phinx\Db\Adapter\AdapterInterface;
  7. use Phinx\Migration\AbstractMigration;
  8. use Phinx\Migration\MigrationInterface;
  9. use Phinx\Util\Util;
  10. use SixShop\Core\Helper;
  11. use SixShop\System\Model\MigrationsModel;
  12. use think\App;
  13. use think\Model;
  14. class Migrate
  15. {
  16. private string $moduleName;
  17. private string $path;
  18. protected ?array $migrations = null;
  19. private $input;
  20. private $output;
  21. protected AdapterInterface $adapter;
  22. protected App $app;
  23. public function __construct(App $app, string $moduleName)
  24. {
  25. $this->app = $app;
  26. $this->moduleName = $moduleName;
  27. $this->path = Helper::extension_path($this->moduleName) . 'database' . DIRECTORY_SEPARATOR . 'migrations';
  28. $this->migrations = $this->getMigrations();
  29. $this->input = null;
  30. $this->output = null;
  31. }
  32. public function install(): array
  33. {
  34. $migrations = $this->getMigrations();
  35. $versions = $this->getVersions();
  36. $currentVersion = $this->getCurrentVersion();
  37. if (empty($versions) && empty($migrations)) {
  38. return [];
  39. }
  40. ksort($migrations);
  41. $installVersions = [];
  42. foreach ($migrations as $migration) {
  43. if ($migration->getVersion() <= $currentVersion) {
  44. continue;
  45. }
  46. if (!in_array($migration->getVersion(), $versions)) {
  47. $installVersions[] = $migration->getVersion();
  48. $this->executeMigration($migration);
  49. }
  50. }
  51. return $installVersions;
  52. }
  53. public function uninstall(): void
  54. {
  55. $migrations = $this->getMigrations();
  56. $versionLog = $this->getVersionLog();
  57. $versions = array_keys($versionLog);
  58. ksort($migrations);
  59. sort($versions);
  60. if (empty($versions)) {
  61. return;
  62. }
  63. krsort($migrations);
  64. foreach ($migrations as $migration) {
  65. if (in_array($migration->getVersion(), $versions)) {
  66. if (isset($versionLog[$migration->getVersion()]) && 0 != $versionLog[$migration->getVersion()]['breakpoint']) {
  67. break;
  68. }
  69. $this->executeMigration($migration, MigrationInterface::DOWN);
  70. }
  71. }
  72. }
  73. public function getMigrationList(): array
  74. {
  75. $migrations = $this->getMigrations();
  76. MigrationsModel::maker(function (Model $model) {
  77. if ($model instanceof MigrationsModel) {
  78. $model->setOption('suffix', $this->moduleName);
  79. }
  80. });
  81. $versionLog = MigrationsModel::column('*', 'version');
  82. foreach ($migrations as $key => $migration) {
  83. $migrations[$key] = $versionLog[$key] ?? ['version'=> $key];
  84. }
  85. return array_values($migrations);
  86. }
  87. protected function getMigrations(): ?array
  88. {
  89. if (null === $this->migrations) {
  90. if (!is_dir($this->path)) {
  91. return [];
  92. }
  93. $allFiles = array_diff(scandir($this->path), ['.', '..']);
  94. $phpFiles = [];
  95. foreach ($allFiles as $file) {
  96. if (pathinfo($file, PATHINFO_EXTENSION) === 'php') {
  97. $phpFiles[] = $this->path . DIRECTORY_SEPARATOR . $file;
  98. }
  99. }
  100. // filter the files to only get the ones that match our naming scheme
  101. $fileNames = [];
  102. /** @var Migrator[] $versions */
  103. $versions = [];
  104. foreach ($phpFiles as $filePath) {
  105. if (Util::isValidMigrationFileName(basename($filePath))) {
  106. $version = Util::getVersionFromFileName(basename($filePath));
  107. if (isset($versions[$version])) {
  108. throw new \InvalidArgumentException(sprintf('Duplicate migration - "%s" has the same version as "%s"', $filePath, $versions[$version]->getVersion()));
  109. }
  110. // convert the filename to a class name
  111. $class = Util::mapFileNameToClassName(basename($filePath));
  112. if (isset($fileNames[$class])) {
  113. throw new \InvalidArgumentException(sprintf('Migration "%s" has the same name as "%s"', basename($filePath), $fileNames[$class]));
  114. }
  115. $fileNames[$class] = basename($filePath);
  116. // load the migration file
  117. /** @noinspection PhpIncludeInspection */
  118. require_once $filePath;
  119. if (!class_exists($class)) {
  120. throw new \InvalidArgumentException(sprintf('Could not find class "%s" in file "%s"', $class, $filePath));
  121. }
  122. // instantiate it
  123. $migration = new $class('default', $version, $this->input, $this->output);
  124. if (!($migration instanceof AbstractMigration)) {
  125. throw new \InvalidArgumentException(sprintf('The class "%s" in file "%s" must extend \Phinx\Migration\AbstractMigration', $class, $filePath));
  126. }
  127. $versions[$version] = $migration;
  128. }
  129. }
  130. ksort($versions);
  131. $this->migrations = $versions;
  132. }
  133. return $this->migrations;
  134. }
  135. protected function getVersions()
  136. {
  137. return $this->getAdapter()->getVersions();
  138. }
  139. protected function getVersionLog()
  140. {
  141. return $this->getAdapter()->getVersionLog();
  142. }
  143. public function getAdapter()
  144. {
  145. if (isset($this->adapter)) {
  146. return $this->adapter;
  147. }
  148. $options = $this->getDbConfig();
  149. $adapterFactory = AdapterFactory::instance();
  150. $adapterFactory->registerAdapter('mysql', ExtensionMysqlAdapter::class);
  151. $adapter = $adapterFactory->getAdapter($options['adapter'], $options);
  152. if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
  153. $adapter = $adapterFactory->getWrapper('prefix', $adapter);
  154. }
  155. $this->adapter = $adapter;
  156. return $adapter;
  157. }
  158. protected function getDbConfig(): array
  159. {
  160. $default = $this->app->config->get('database.default');
  161. $config = $this->app->config->get("database.connections.{$default}");
  162. if (0 == $config['deploy']) {
  163. $dbConfig = [
  164. 'adapter' => $config['type'],
  165. 'host' => $config['hostname'],
  166. 'name' => $config['database'],
  167. 'user' => $config['username'],
  168. 'pass' => $config['password'],
  169. 'port' => $config['hostport'],
  170. 'charset' => $config['charset'],
  171. 'suffix' => $config['suffix'] ?? '',
  172. 'table_prefix' => $config['prefix'],
  173. ];
  174. } else {
  175. $dbConfig = [
  176. 'adapter' => explode(',', $config['type'])[0],
  177. 'host' => explode(',', $config['hostname'])[0],
  178. 'name' => explode(',', $config['database'])[0],
  179. 'user' => explode(',', $config['username'])[0],
  180. 'pass' => explode(',', $config['password'])[0],
  181. 'port' => explode(',', $config['hostport'])[0],
  182. 'charset' => explode(',', $config['charset'])[0],
  183. 'suffix' => explode(',', $config['suffix'] ?? '')[0],
  184. 'table_prefix' => explode(',', $config['prefix'])[0],
  185. ];
  186. }
  187. $table = $this->app->config->get('database.extension_migration_table', 'migrations_' . $this->moduleName);
  188. $dbConfig['migration_table'] = $dbConfig['table_prefix'] . $table;
  189. $dbConfig['version_order'] = Config::VERSION_ORDER_CREATION_TIME;
  190. return $dbConfig;
  191. }
  192. protected function getCurrentVersion()
  193. {
  194. $versions = $this->getVersions();
  195. $version = 0;
  196. if (!empty($versions)) {
  197. $version = end($versions);
  198. }
  199. return $version;
  200. }
  201. protected function executeMigration(MigrationInterface $migration, $direction = MigrationInterface::UP)
  202. {
  203. $startTime = time();
  204. $direction = (MigrationInterface::UP === $direction) ? MigrationInterface::UP : MigrationInterface::DOWN;
  205. $migration->setMigratingUp($direction === MigrationInterface::UP);
  206. $migration->setAdapter($this->getAdapter());
  207. $migration->preFlightCheck();
  208. if (method_exists($migration, MigrationInterface::INIT)) {
  209. $migration->{MigrationInterface::INIT}();
  210. }
  211. // begin the transaction if the adapter supports it
  212. if ($this->getAdapter()->hasTransactions()) {
  213. $this->getAdapter()->beginTransaction();
  214. }
  215. // Run the migration
  216. if (method_exists($migration, MigrationInterface::CHANGE)) {
  217. if (MigrationInterface::DOWN === $direction) {
  218. // Create an instance of the ProxyAdapter so we can record all
  219. // of the migration commands for reverse playback
  220. /** @var \Phinx\Db\Adapter\ProxyAdapter $proxyAdapter */
  221. $proxyAdapter = AdapterFactory::instance()->getWrapper('proxy', $this->getAdapter());
  222. $migration->setAdapter($proxyAdapter);
  223. $migration->{MigrationInterface::CHANGE}();
  224. $proxyAdapter->executeInvertedCommands();
  225. $migration->setAdapter($this->getAdapter());
  226. } else {
  227. /** @noinspection PhpUndefinedMethodInspection */
  228. $migration->change();
  229. }
  230. } else {
  231. $migration->{$direction}();
  232. }
  233. // commit the transaction if the adapter supports it
  234. if ($this->getAdapter()->hasTransactions()) {
  235. $this->getAdapter()->commitTransaction();
  236. }
  237. $migration->postFlightCheck();
  238. // Record it in the database
  239. $this->getAdapter()
  240. ->migrated($migration, $direction, date('Y-m-d H:i:s', $startTime), date('Y-m-d H:i:s', time()));
  241. }
  242. }