Migrator.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * The Minz_Migrator helps to migrate data (in a database or not) or the
  5. * architecture of a Minz application.
  6. *
  7. * @author Marien Fressinaud <dev@marienfressinaud.fr>
  8. * @license http://www.gnu.org/licenses/agpl-3.0.en.html AGPL
  9. */
  10. class Minz_Migrator
  11. {
  12. /** @var array<string> */
  13. private array $applied_versions;
  14. /** @var array<callable> */
  15. private array $migrations = [];
  16. /**
  17. * Execute a list of migrations, skipping versions indicated in a file
  18. *
  19. * @param string $migrations_path
  20. * @param string $applied_migrations_path
  21. *
  22. * @return true|string Returns true if execute succeeds to apply
  23. * migrations, or a string if it fails.
  24. * @throws DomainException if there is no migrations corresponding to the
  25. * given version (can happen if version file has
  26. * been modified, or migrations path cannot be
  27. * read).
  28. *
  29. * @throws BadFunctionCallException if a callback isn’t callable.
  30. */
  31. public static function execute(string $migrations_path, string $applied_migrations_path) {
  32. $applied_migrations = @file_get_contents($applied_migrations_path);
  33. if ($applied_migrations === false) {
  34. return "Cannot open the {$applied_migrations_path} file";
  35. }
  36. $applied_migrations = array_filter(explode("\n", $applied_migrations));
  37. $migration_files = scandir($migrations_path) ?: [];
  38. $migration_files = array_filter($migration_files, static function (string $filename) {
  39. $file_extension = pathinfo($filename, PATHINFO_EXTENSION);
  40. return $file_extension === 'php';
  41. });
  42. $migration_versions = array_map(static function (string $filename) {
  43. return basename($filename, '.php');
  44. }, $migration_files);
  45. // We apply a "low-cost" comparison to avoid to include the migration
  46. // files at each run. It is equivalent to the upToDate method.
  47. if (count($applied_migrations) === count($migration_versions) &&
  48. empty(array_diff($applied_migrations, $migration_versions))) {
  49. // already at the latest version, so there is nothing more to do
  50. return true;
  51. }
  52. $lock_path = $applied_migrations_path . '.lock';
  53. if (!@mkdir($lock_path, 0770, true)) {
  54. // Someone is probably already executing the migrations (the folder
  55. // already exists).
  56. // We should probably return something else, but we don’t want the
  57. // user to think there is an error (it’s normal workflow), so let’s
  58. // stick to this solution for now.
  59. // Another option would be to show him a maintenance page.
  60. Minz_Log::warning(
  61. 'A request has been served while the application wasn’t up-to-date. '
  62. . 'Too many of these errors probably means a previous migration failed.'
  63. );
  64. return true;
  65. }
  66. $migrator = new self($migrations_path);
  67. $migrator->setAppliedVersions($applied_migrations);
  68. $results = $migrator->migrate();
  69. foreach ($results as $migration => $result) {
  70. if ($result === true) {
  71. $result = 'OK';
  72. } elseif ($result === false) {
  73. $result = 'KO';
  74. }
  75. Minz_Log::notice("Migration {$migration}: {$result}");
  76. }
  77. $applied_versions = implode("\n", $migrator->appliedVersions());
  78. $saved = file_put_contents($applied_migrations_path, $applied_versions);
  79. if (!@rmdir($lock_path)) {
  80. Minz_Log::error(
  81. 'We weren’t able to unlink the migration executing folder, '
  82. . 'you might want to delete yourself: ' . $lock_path
  83. );
  84. // we don’t return early because the migrations could have been
  85. // applied successfully. This file is not "critical" if not removed
  86. // and more errors will eventually appear in the logs.
  87. }
  88. if ($saved === false) {
  89. return "Cannot save the {$applied_migrations_path} file";
  90. }
  91. if (!$migrator->upToDate()) {
  92. // still not up to date? It means last migration failed.
  93. return trim('A migration failed to be applied, please see previous logs.' . "\n" . implode("\n", $results));
  94. }
  95. return true;
  96. }
  97. /**
  98. * Create a Minz_Migrator instance. If directory is given, it'll load the
  99. * migrations from it.
  100. *
  101. * All the files in the directory must declare a class named
  102. * <app_name>_Migration_<filename> with a static `migrate` method.
  103. *
  104. * - <app_name> is the application name declared in the APP_NAME constant
  105. * - <filename> is the migration file name, without the `.php` extension
  106. *
  107. * The files starting with a dot are ignored.
  108. *
  109. * @throws BadFunctionCallException if a callback isn’t callable (i.e. cannot call a migrate method).
  110. */
  111. public function __construct(?string $directory = null) {
  112. $this->applied_versions = [];
  113. if ($directory == null || !is_dir($directory)) {
  114. return;
  115. }
  116. foreach (scandir($directory) ?: [] as $filename) {
  117. $file_extension = pathinfo($filename, PATHINFO_EXTENSION);
  118. if ($file_extension !== 'php') {
  119. continue;
  120. }
  121. $filepath = $directory . '/' . $filename;
  122. $migration_version = basename($filename, '.php');
  123. $migration_class = APP_NAME . "_Migration_" . $migration_version;
  124. $migration_callback = $migration_class . '::migrate';
  125. $include_result = @include_once($filepath);
  126. if (!$include_result) {
  127. Minz_Log::error(
  128. "{$filepath} migration file cannot be loaded.",
  129. ADMIN_LOG
  130. );
  131. }
  132. if (!is_callable($migration_callback)) {
  133. throw new BadFunctionCallException("{$migration_version} migration cannot be called.");
  134. }
  135. $this->addMigration($migration_version, $migration_callback);
  136. }
  137. }
  138. /**
  139. * Register a migration into the migration system.
  140. *
  141. * @param string $version The version of the migration (be careful, migrations
  142. * are sorted with the `strnatcmp` function)
  143. * @param callable $callback The migration function to execute, it should
  144. * return true on success and must return false
  145. * on error
  146. */
  147. public function addMigration(string $version, callable $callback): void {
  148. $this->migrations[$version] = $callback;
  149. }
  150. /**
  151. * Return the list of migrations, sorted with `strnatcmp`
  152. *
  153. * @see https://www.php.net/manual/en/function.strnatcmp.php
  154. *
  155. * @return array<string,callable>
  156. */
  157. public function migrations(): array {
  158. $migrations = $this->migrations;
  159. uksort($migrations, 'strnatcmp');
  160. return $migrations;
  161. }
  162. /**
  163. * Set the applied versions of the application.
  164. *
  165. * @param array<string> $versions
  166. *
  167. * @throws DomainException if there is no migrations corresponding to a version
  168. */
  169. public function setAppliedVersions(array $versions): void {
  170. foreach ($versions as $version) {
  171. $version = trim($version);
  172. if (!isset($this->migrations[$version])) {
  173. throw new DomainException("{$version} migration does not exist.");
  174. }
  175. $this->applied_versions[] = $version;
  176. }
  177. }
  178. /**
  179. * @return string[]
  180. */
  181. public function appliedVersions(): array {
  182. $versions = $this->applied_versions;
  183. usort($versions, 'strnatcmp');
  184. return $versions;
  185. }
  186. /**
  187. * Return the list of available versions, sorted with `strnatcmp`
  188. *
  189. * @see https://www.php.net/manual/en/function.strnatcmp.php
  190. *
  191. * @return string[]
  192. */
  193. public function versions(): array {
  194. $migrations = $this->migrations();
  195. return array_keys($migrations);
  196. }
  197. /**
  198. * @return bool Return true if the application is up-to-date, false otherwise.
  199. * If no migrations are registered, it always returns true.
  200. */
  201. public function upToDate(): bool {
  202. // Counting versions is enough since we cannot apply a version which
  203. // doesn’t exist (see setAppliedVersions method).
  204. return count($this->versions()) === count($this->applied_versions);
  205. }
  206. /**
  207. * Migrate the system to the latest version.
  208. *
  209. * It only executes migrations AFTER the current version. If a migration
  210. * returns false or fails, it immediately stops the process.
  211. *
  212. * If the migration doesn’t return false nor raise an exception, it is
  213. * considered as successful. It is considered as good practice to return
  214. * true on success though.
  215. *
  216. * @return array<string|bool> Return the results of each executed migration. If an
  217. * exception was raised in a migration, its result is set to
  218. * the exception message.
  219. */
  220. public function migrate(): array {
  221. $result = [];
  222. foreach ($this->migrations() as $version => $callback) {
  223. if (in_array($version, $this->applied_versions, true)) {
  224. // the version is already applied so we skip this migration
  225. continue;
  226. }
  227. try {
  228. $migration_result = $callback();
  229. $result[$version] = $migration_result;
  230. } catch (Exception $e) {
  231. $migration_result = false;
  232. $result[$version] = $e->getMessage();
  233. }
  234. if ($migration_result === false) {
  235. break;
  236. }
  237. $this->applied_versions[] = $version;
  238. }
  239. return $result;
  240. }
  241. }