Migrator.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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<string> */
  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.
  111. * cannot call a migrate method).
  112. */
  113. public function __construct(?string $directory = null) {
  114. $this->applied_versions = [];
  115. if ($directory == null || !is_dir($directory)) {
  116. return;
  117. }
  118. foreach (scandir($directory) as $filename) {
  119. $file_extension = pathinfo($filename, PATHINFO_EXTENSION);
  120. if ($file_extension !== 'php') {
  121. continue;
  122. }
  123. $filepath = $directory . '/' . $filename;
  124. $migration_version = basename($filename, '.php');
  125. $migration_class = APP_NAME . "_Migration_" . $migration_version;
  126. $migration_callback = $migration_class . '::migrate';
  127. $include_result = @include_once($filepath);
  128. if (!$include_result) {
  129. Minz_Log::error(
  130. "{$filepath} migration file cannot be loaded.",
  131. ADMIN_LOG
  132. );
  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. * @throws BadFunctionCallException if the callback isn't callable.
  147. */
  148. public function addMigration(string $version, ?callable $callback): void {
  149. if (!is_callable($callback)) {
  150. throw new BadFunctionCallException("{$version} migration cannot be called.");
  151. }
  152. $this->migrations[$version] = $callback;
  153. }
  154. /**
  155. * Return the list of migrations, sorted with `strnatcmp`
  156. *
  157. * @see https://www.php.net/manual/en/function.strnatcmp.php
  158. *
  159. * @return array<string,callable>
  160. */
  161. public function migrations(): array {
  162. $migrations = $this->migrations;
  163. uksort($migrations, 'strnatcmp');
  164. return $migrations;
  165. }
  166. /**
  167. * Set the applied versions of the application.
  168. *
  169. * @param array<string> $versions
  170. *
  171. * @throws DomainException if there is no migrations corresponding to a version
  172. */
  173. public function setAppliedVersions(array $versions): void {
  174. foreach ($versions as $version) {
  175. $version = trim($version);
  176. if (!isset($this->migrations[$version])) {
  177. throw new DomainException("{$version} migration does not exist.");
  178. }
  179. $this->applied_versions[] = $version;
  180. }
  181. }
  182. /**
  183. * @return string[]
  184. */
  185. public function appliedVersions(): array {
  186. $versions = $this->applied_versions;
  187. usort($versions, 'strnatcmp');
  188. return $versions;
  189. }
  190. /**
  191. * Return the list of available versions, sorted with `strnatcmp`
  192. *
  193. * @see https://www.php.net/manual/en/function.strnatcmp.php
  194. *
  195. * @return string[]
  196. */
  197. public function versions(): array {
  198. $migrations = $this->migrations();
  199. return array_keys($migrations);
  200. }
  201. /**
  202. * @return bool Return true if the application is up-to-date, false otherwise.
  203. * If no migrations are registered, it always returns true.
  204. */
  205. public function upToDate(): bool {
  206. // Counting versions is enough since we cannot apply a version which
  207. // doesn't exist (see setAppliedVersions method).
  208. return count($this->versions()) === count($this->applied_versions);
  209. }
  210. /**
  211. * Migrate the system to the latest version.
  212. *
  213. * It only executes migrations AFTER the current version. If a migration
  214. * returns false or fails, it immediately stops the process.
  215. *
  216. * If the migration doesn't return false nor raise an exception, it is
  217. * considered as successful. It is considered as good practice to return
  218. * true on success though.
  219. *
  220. * @return array<string|bool> Return the results of each executed migration. If an
  221. * exception was raised in a migration, its result is set to
  222. * the exception message.
  223. */
  224. public function migrate(): array {
  225. $result = [];
  226. foreach ($this->migrations() as $version => $callback) {
  227. if (in_array($version, $this->applied_versions)) {
  228. // the version is already applied so we skip this migration
  229. continue;
  230. }
  231. try {
  232. $migration_result = $callback();
  233. $result[$version] = $migration_result;
  234. } catch (Exception $e) {
  235. $migration_result = false;
  236. $result[$version] = $e->getMessage();
  237. }
  238. if ($migration_result === false) {
  239. break;
  240. }
  241. $this->applied_versions[] = $version;
  242. }
  243. return $result;
  244. }
  245. }