Migrator.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. if ($applied_migrations) {
  67. $migrator->setAppliedVersions($applied_migrations);
  68. }
  69. $results = $migrator->migrate();
  70. foreach ($results as $migration => $result) {
  71. if ($result === true) {
  72. $result = 'OK';
  73. } elseif ($result === false) {
  74. $result = 'KO';
  75. }
  76. Minz_Log::notice("Migration {$migration}: {$result}");
  77. }
  78. $applied_versions = implode("\n", $migrator->appliedVersions());
  79. $saved = file_put_contents($applied_migrations_path, $applied_versions);
  80. if (!@rmdir($lock_path)) {
  81. Minz_Log::error(
  82. 'We weren’t able to unlink the migration executing folder, '
  83. . 'you might want to delete yourself: ' . $lock_path
  84. );
  85. // we don’t return early because the migrations could have been
  86. // applied successfully. This file is not "critical" if not removed
  87. // and more errors will eventually appear in the logs.
  88. }
  89. if ($saved === false) {
  90. return "Cannot save the {$applied_migrations_path} file";
  91. }
  92. if (!$migrator->upToDate()) {
  93. // still not up to date? It means last migration failed.
  94. return trim('A migration failed to be applied, please see previous logs.' . "\n" . implode("\n", $results));
  95. }
  96. return true;
  97. }
  98. /**
  99. * Create a Minz_Migrator instance. If directory is given, it'll load the
  100. * migrations from it.
  101. *
  102. * All the files in the directory must declare a class named
  103. * <app_name>_Migration_<filename> with a static `migrate` method.
  104. *
  105. * - <app_name> is the application name declared in the APP_NAME constant
  106. * - <filename> is the migration file name, without the `.php` extension
  107. *
  108. * The files starting with a dot are ignored.
  109. *
  110. * @throws BadFunctionCallException if a callback isn’t callable (i.e. cannot call a migrate method).
  111. */
  112. public function __construct(?string $directory = null) {
  113. $this->applied_versions = [];
  114. if ($directory == null || !is_dir($directory)) {
  115. return;
  116. }
  117. foreach (scandir($directory) ?: [] as $filename) {
  118. $file_extension = pathinfo($filename, PATHINFO_EXTENSION);
  119. if ($file_extension !== 'php') {
  120. continue;
  121. }
  122. $filepath = $directory . '/' . $filename;
  123. $migration_version = basename($filename, '.php');
  124. $migration_class = APP_NAME . "_Migration_" . $migration_version;
  125. $migration_callback = $migration_class . '::migrate';
  126. $include_result = @include_once($filepath);
  127. if (!$include_result) {
  128. Minz_Log::error(
  129. "{$filepath} migration file cannot be loaded.",
  130. ADMIN_LOG
  131. );
  132. }
  133. if (!is_callable($migration_callback)) {
  134. throw new BadFunctionCallException("{$migration_version} migration cannot be called.");
  135. }
  136. $this->addMigration($migration_version, $migration_callback);
  137. }
  138. }
  139. /**
  140. * Register a migration into the migration system.
  141. *
  142. * @param string $version The version of the migration (be careful, migrations
  143. * are sorted with the `strnatcmp` function)
  144. * @param callable $callback The migration function to execute, it should
  145. * return true on success and must return false
  146. * on error
  147. */
  148. public function addMigration(string $version, callable $callback): void {
  149. $this->migrations[$version] = $callback;
  150. }
  151. /**
  152. * Return the list of migrations, sorted with `strnatcmp`
  153. *
  154. * @see https://www.php.net/manual/en/function.strnatcmp.php
  155. *
  156. * @return array<string,callable>
  157. */
  158. public function migrations(): array {
  159. $migrations = $this->migrations;
  160. uksort($migrations, 'strnatcmp');
  161. return $migrations;
  162. }
  163. /**
  164. * Set the applied versions of the application.
  165. *
  166. * @param array<string> $versions
  167. *
  168. * @throws DomainException if there is no migrations corresponding to a version
  169. */
  170. public function setAppliedVersions(array $versions): void {
  171. foreach ($versions as $version) {
  172. $version = trim($version);
  173. if (!isset($this->migrations[$version])) {
  174. throw new DomainException("{$version} migration does not exist.");
  175. }
  176. $this->applied_versions[] = $version;
  177. }
  178. }
  179. /**
  180. * @return string[]
  181. */
  182. public function appliedVersions(): array {
  183. $versions = $this->applied_versions;
  184. usort($versions, 'strnatcmp');
  185. return $versions;
  186. }
  187. /**
  188. * Return the list of available versions, sorted with `strnatcmp`
  189. *
  190. * @see https://www.php.net/manual/en/function.strnatcmp.php
  191. *
  192. * @return string[]
  193. */
  194. public function versions(): array {
  195. $migrations = $this->migrations();
  196. return array_keys($migrations);
  197. }
  198. /**
  199. * @return bool Return true if the application is up-to-date, false otherwise.
  200. * If no migrations are registered, it always returns true.
  201. */
  202. public function upToDate(): bool {
  203. // Counting versions is enough since we cannot apply a version which
  204. // doesn’t exist (see setAppliedVersions method).
  205. return count($this->versions()) === count($this->applied_versions);
  206. }
  207. /**
  208. * Migrate the system to the latest version.
  209. *
  210. * It only executes migrations AFTER the current version. If a migration
  211. * returns false or fails, it immediately stops the process.
  212. *
  213. * If the migration doesn’t return false nor raise an exception, it is
  214. * considered as successful. It is considered as good practice to return
  215. * true on success though.
  216. *
  217. * @return array<string|bool> Return the results of each executed migration. If an
  218. * exception was raised in a migration, its result is set to
  219. * the exception message.
  220. */
  221. public function migrate(): array {
  222. $result = [];
  223. foreach ($this->migrations() as $version => $callback) {
  224. if (in_array($version, $this->applied_versions, true)) {
  225. // the version is already applied so we skip this migration
  226. continue;
  227. }
  228. try {
  229. $migration_result = $callback();
  230. $result[$version] = $migration_result;
  231. } catch (Exception $e) {
  232. $migration_result = false;
  233. $result[$version] = $e->getMessage();
  234. }
  235. if ($migration_result === false) {
  236. break;
  237. }
  238. $this->applied_versions[] = $version;
  239. }
  240. return $result;
  241. }
  242. }