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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
<?php
namespace Tev\Database\CustomTables;
use wpdb;
use Tev\Application\Application;
/**
* Run install scripts for custom database tables.
*
* See: http://codex.wordpress.org/Creating_Tables_with_Plugins for more
* information.
*/
abstract class AbstractInstaller
{
/**
* WPDB API.
*
* @var \wpdb
*/
protected $wpdb;
/**
* Application container.
*
* @var \Tev\Application\Application
*/
protected $app;
/**
* Constructor.
*
* Inject dependencies.
*
* @param \wpdb $wpdb WPDB API
* @param \Tev\Application\Application $app Application container
* @return void
*/
public function __construct(wpdb $wpdb, Application $app)
{
$this->wpdb = $wpdb;
$this->app = $app;
}
/**
* Return the SQL statement that will install/update the database for
* this installer.
*
* See http://codex.wordpress.org/Creating_Tables_with_Plugins#Creating_or_Updating_the_Table
* for SQL idiosyncrasies in Wordpress.
*
* @return string SQL string
*/
abstract protected function getSql();
/**
* Get the current database version.
*
* Should be updated every time the database needs to be updated.
*
* @return string Semver string, like 1.0.0
*/
abstract protected function getVersion();
/**
* Install the database for this first.
*
* @return void
*/
public function install()
{
$this->run();
}
/**
* Update the database if it's out of date.
*
* @return void
*/
public function update()
{
if ($this->getVersion() !== $this->getCurrentVersion()) {
$this->run();
}
}
/**
* Run database scripts.
*
* See http://codex.wordpress.org/Creating_Tables_with_Plugins#Creating_or_Updating_the_Table
* for SQL idiosyncrasies in Wordpress.
*
* @return void
*/
protected function run()
{
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($this->getSql());
$this->setCurrentVersion();
}
/**
* Get the current installed database version.
*
* @return string|null
*/
private function getCurrentVersion()
{
return get_option($this->getVersionOptionKey(), null);
}
/**
* Set the current installed database version.
*
* @return \Lsg\Database\LocationsInstaller This, for chaining
*/
private function setCurrentVersion()
{
if ($this->getCurrentVersion() !== null) {
update_option($this->getVersionOptionKey(), $this->getVersion());
} else {
add_option($this->getVersionOptionKey(), $this->getVersion());
}
return $this;
}
/**
* Get the option key to store the database version in.
*
* @return string
*/
private function getVersionOptionKey()
{
return strtolower(str_replace('\\', '_', get_class($this))) . '_version';
}
}