4
0

Migrator.php 8.5 KB

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