Refactor Migrator to support functional sql generators.

This commit is contained in:
marco
2015-08-03 17:12:05 +02:00
parent cd990f40ce
commit dc00abb0da
2 changed files with 50 additions and 10 deletions

View File

@@ -10,19 +10,57 @@ class Migrator {
function __construct() {
$this->prefix = Env::$db_prefix . 'mailpoet_';
$this->charset = Env::$db_charset;
$this->models = array(
'subscriber',
'setting'
);
}
function up() {
global $wpdb;
dbDelta($this->subscribers());
$migrate = function($model) {
dbDelta($this->$model());
};
array_map($migrate, $this->models);
}
function subscribers() {
$table = $this->prefix . 'subscriber';
$sql = "CREATE TABLE " . $table . " (
id mediumint(9) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
);";
return $sql;
function down() {
global $wpdb;
$drop_table = function($model) {
$table = $this->prefix . $model;
$wpdb->query("DROP TABLE {$table}");
};
array_map($drop_table, $this->models);
}
function subscriber() {
$attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'PRIMARY KEY (id)'
);
return $this->sqlify(__FUNCTION__, $attributes);
}
function setting() {
$attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'PRIMARY KEY (id)'
);
return $this->sqlify(__FUNCTION__, $attributes);
}
private function sqlify($model, $attributes) {
$table = $this->prefix . $model;
$sql = array();
$sql[] = "CREATE TABLE " . $table . " (";
$sql = array_merge($sql, $attributes);
$sql[] = ")" . $this->charset . ";";
return implode("\n", $sql);
}
}

View File

@@ -7,8 +7,10 @@ class MigratorCest {
$this->migrator = new Migrator();
}
public function itCreatesTheSubscriberTable() {
// Can't be tested because of WordPress.
public function itCanGenerateSubscriberSql() {
$subscriber_sql = $this->migrator->subscriber();
$expected_table = $this->migrator->prefix . 'subscriber';
expect($subscriber_sql)->contains($expected_table);
}
public function _after() {