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() { function __construct() {
$this->prefix = Env::$db_prefix . 'mailpoet_'; $this->prefix = Env::$db_prefix . 'mailpoet_';
$this->charset = Env::$db_charset; $this->charset = Env::$db_charset;
$this->models = array(
'subscriber',
'setting'
);
} }
function up() { function up() {
global $wpdb; global $wpdb;
dbDelta($this->subscribers());
$migrate = function($model) {
dbDelta($this->$model());
};
array_map($migrate, $this->models);
} }
function subscribers() { function down() {
$table = $this->prefix . 'subscriber'; global $wpdb;
$sql = "CREATE TABLE " . $table . " (
id mediumint(9) NOT NULL AUTO_INCREMENT, $drop_table = function($model) {
PRIMARY KEY (id) $table = $this->prefix . $model;
);"; $wpdb->query("DROP TABLE {$table}");
return $sql; };
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(); $this->migrator = new Migrator();
} }
public function itCreatesTheSubscriberTable() { public function itCanGenerateSubscriberSql() {
// Can't be tested because of WordPress. $subscriber_sql = $this->migrator->subscriber();
$expected_table = $this->migrator->prefix . 'subscriber';
expect($subscriber_sql)->contains($expected_table);
} }
public function _after() { public function _after() {