aboutsummaryrefslogtreecommitdiffhomepage
path: root/WpfTest/Db/Migrator.php
diff options
context:
space:
mode:
authorwinter2024-12-07 21:44:42 +0000
committerwinter2024-12-07 21:44:42 +0000
commita84232811dadccf7047424f27340a7f9847bedff (patch)
treea6a0823c8b9485b6a5b60ea7ae854f9511a6ae1e /WpfTest/Db/Migrator.php
parente1ad307b531c27ec6bfaf8b4d018991b0d4a78f3 (diff)
many many changes but actors are loaded from db now
Diffstat (limited to 'WpfTest/Db/Migrator.php')
-rw-r--r--WpfTest/Db/Migrator.php52
1 files changed, 52 insertions, 0 deletions
diff --git a/WpfTest/Db/Migrator.php b/WpfTest/Db/Migrator.php
new file mode 100644
index 0000000..ea7f92a
--- /dev/null
+++ b/WpfTest/Db/Migrator.php
@@ -0,0 +1,52 @@
+<?php
+namespace WpfTest\Db;
+
+use WpfTest\Db;
+use WpfTest\Singleton;
+
+class Migrator extends Singleton {
+ private array $migrations = [];
+
+ public function register(int $newVersion, callable $fn) {
+ $this->migrations[$newVersion] = $fn;
+ }
+
+ /**
+ * Runs all available migrations
+ * @return void
+ */
+ public function migrate() {
+ $db = Db::getInstance();
+ $currentVersion = null;
+ try {
+ $currentVersion = $db->getDbVersion();
+ error_log('starting on version ' . $currentVersion);
+ } catch (\PDOException $e) {
+ if ($e->getCode() == '42P01') { // undefined table
+ error_log("initialising database because db version table doesn't exist");
+ $db->runInitialSchema();
+ $currentVersion = $db->getDbVersion();
+ error_log('starting on version ' . $currentVersion);
+ } else
+ throw $e;
+ }
+
+ // find migrations that haven't been run yet
+ $available = array_filter($this->migrations, function (int $key) use ($currentVersion) {
+ return $key > $currentVersion;
+ }, ARRAY_FILTER_USE_KEY);
+
+ try {
+ // run them in order (at least they should be in order?)
+ foreach (array_keys($available) as $version) {
+ $fn = $available[$version];
+ $filename = basename((new \ReflectionFunction($fn))->getFileName());
+ error_log("running migration $filename");
+ $available[$version]($db->getPdo());
+ $db->setDbVersion($version);
+ }
+ } finally {
+ error_log('now on version ' . $db->getDbVersion());
+ }
+ }
+} \ No newline at end of file