Migrator.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 */
  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. * @throws BadFunctionCallException if a callback isn't callable.
  22. * @throws DomainException if there is no migrations corresponding to the
  23. * given version (can happen if version file has
  24. * been modified, or migrations path cannot be
  25. * read).
  26. *
  27. * @return boolean|string Returns true if execute succeeds to apply
  28. * migrations, or a string if it fails.
  29. */
  30. public static function execute($migrations_path, $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, function ($filename) {
  38. return $filename[0] !== '.';
  39. });
  40. $migration_versions = array_map(function ($filename) {
  41. return basename($filename, '.php');
  42. }, $migration_files);
  43. // We apply a "low-cost" comparison to avoid to include the migration
  44. // files at each run. It is equivalent to the upToDate method.
  45. if (count($applied_migrations) === count($migration_versions) &&
  46. empty(array_diff($applied_migrations, $migration_versions))) {
  47. // already at the latest version, so there is nothing more to do
  48. return true;
  49. }
  50. $lock_path = $applied_migrations_path . '.lock';
  51. if (!@mkdir($lock_path)) {
  52. // Someone is probably already executing the migrations (the folder
  53. // already exists).
  54. // We should probably return something else, but we don't want the
  55. // user to think there is an error (it's normal workflow), so let's
  56. // stick to this solution for now.
  57. // Another option would be to show him a maintenance page.
  58. Minz_Log::warning(
  59. 'A request has been served while the application wasn’t up-to-date. '
  60. . 'Too many of these errors probably means a previous migration failed.'
  61. );
  62. return true;
  63. }
  64. $migrator = new self($migrations_path);
  65. if ($applied_migrations) {
  66. $migrator->setAppliedVersions($applied_migrations);
  67. }
  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. * @param string|null $directory
  110. *
  111. * @throws BadFunctionCallException if a callback isn't callable (i.e.
  112. * cannot call a migrate method).
  113. */
  114. public function __construct($directory = null) {
  115. $this->applied_versions = [];
  116. if ($directory == null || !is_dir($directory)) {
  117. return;
  118. }
  119. foreach (scandir($directory) as $filename) {
  120. if ($filename[0] === '.') {
  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($version, $callback) {
  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
  160. */
  161. public function migrations() {
  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($versions) {
  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() {
  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() {
  198. $migrations = $this->migrations();
  199. return array_keys($migrations);
  200. }
  201. /**
  202. * @return boolean Return true if the application is up-to-date, false
  203. * otherwise. If no migrations are registered, it always
  204. * returns true.
  205. */
  206. public function upToDate() {
  207. // Counting versions is enough since we cannot apply a version which
  208. // doesn't exist (see setAppliedVersions method).
  209. return count($this->versions()) === count($this->applied_versions);
  210. }
  211. /**
  212. * Migrate the system to the latest version.
  213. *
  214. * It only executes migrations AFTER the current version. If a migration
  215. * returns false or fails, it immediately stops the process.
  216. *
  217. * If the migration doesn't return false nor raise an exception, it is
  218. * considered as successful. It is considered as good practice to return
  219. * true on success though.
  220. *
  221. * @return array Return the results of each executed migration. If an
  222. * exception was raised in a migration, its result is set to
  223. * the exception message.
  224. */
  225. public function migrate() {
  226. $result = [];
  227. foreach ($this->migrations() as $version => $callback) {
  228. if (in_array($version, $this->applied_versions)) {
  229. // the version is already applied so we skip this migration
  230. continue;
  231. }
  232. try {
  233. $migration_result = $callback();
  234. $result[$version] = $migration_result;
  235. } catch (Exception $e) {
  236. $migration_result = false;
  237. $result[$version] = $e->getMessage();
  238. }
  239. if ($migration_result === false) {
  240. break;
  241. }
  242. $this->applied_versions[] = $version;
  243. }
  244. return $result;
  245. }
  246. }