blob: a1b4e8b35e6ce83f5119862f5ca32543d8f024ec (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
<?php
namespace Digitigrade\Db;
use Digitigrade\Db;
use Digitigrade\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());
}
}
}
|