From dc00abb0da2d6db6feedff36c2b6cc35d0fed8ab Mon Sep 17 00:00:00 2001 From: marco Date: Mon, 3 Aug 2015 17:12:05 +0200 Subject: [PATCH] Refactor Migrator to support functional sql generators. --- lib/config/migrator.php | 54 +++++++++++++++++++++++++++++++------ tests/unit/MigratorCest.php | 6 +++-- 2 files changed, 50 insertions(+), 10 deletions(-) diff --git a/lib/config/migrator.php b/lib/config/migrator.php index 9d49f6bcab..4cd5248bc8 100644 --- a/lib/config/migrator.php +++ b/lib/config/migrator.php @@ -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); } } diff --git a/tests/unit/MigratorCest.php b/tests/unit/MigratorCest.php index 762003385c..1e54915dc2 100644 --- a/tests/unit/MigratorCest.php +++ b/tests/unit/MigratorCest.php @@ -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() {