diff options
Diffstat (limited to 'WpfTest/Db/Migrator.php')
| -rw-r--r-- | WpfTest/Db/Migrator.php | 52 |
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 |
