-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabase.php
More file actions
193 lines (161 loc) · 5.93 KB
/
Copy pathDatabase.php
File metadata and controls
193 lines (161 loc) · 5.93 KB
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
<?php
namespace CodeBeater;
class Database {
private $connection = null;
private static $instance = null;
private static $migrationPath = null;
public function __construct(
$hostname,
$database,
$user,
$password,
$migrationPath = "migrations/"
) {
$this->connection = new PDO("mysql:host={$hostname};dbname={$database};charset=utf8", $user, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->migrationPath = $migrationPath . "/";
}
public static function getInstance(
$hostname = null,
$database = null,
$user = null,
$password = null,
$migrationPath = null
) {
if (!isset(static::$instance)) {
if (!isset($hostname) || !isset($database) || !isset($user) || !isset($password)) {
throw new Exception("Attempted to get database instance without one being available.");
return false;
}
static::$instance = new static($hostname, $database, $user, $password, $migrationPath);
}
return static::$instance;
}
public function getConnection() {
return $this->connection;
}
public function runMigrations() {
$this->setupMigrations();
$latestMigration = $this->getLatestMigration();
//Getting all currently available migration files
$possibleMigrations = scandir($this->migrationPath, SCANDIR_SORT_ASCENDING);
foreach ($possibleMigrations as $migration) {
if ($migration == "." || $migration == "..") {
continue;
}
//Parsing migration name and checking if the id is bigger than the last ran migration
$migrationMeta = $this->parseMigrationMeta($migration);
//Running the migration
if ($migrationMeta['id'] > $latestMigration) {
$success = $this->executeMigration($this->migrationPath . $migration, "UP");
//If successful, register it in the migraitons table
if ($success) {
$latestMigration = $migrationMeta['id'];
$this->registerMigration($migrationMeta['id'], $migration);
} else {
throw new Exception("There was an error trying to run a migration ({$migration})");
}
}
}
}
private function registerMigration($id, $file) {
$stmt = $this->getConnection()->prepare("INSERT INTO `migrations` (`id`, `file`) VALUES (:id, :file)");
$stmt->execute(array(
":id" => $id,
":file" => $file
));
return;
}
private function executeMigration($path, $direction) {
$validDirections = ["UP", "DOWN"];
if (!in_array($direction, $validDirections)) {
throw new Exception("Invalid migration direction ({$direction}) for migration {$path}");
}
//Getting migration contents and preparing query
$migration = $this->parseMigration($path);
$stmt = $this->getConnection()->prepare($migration[$direction]);
$stmt->execute();
return ($stmt->errorCode() === "00000");
}
private function getLatestMigration() {
//Attempting to get the latest migraiton on the database
$getLatestMigration = $this->getConnection()->prepare("SELECT * FROM `migrations` WHERE 1 ORDER BY `id` DESC LIMIT 1");
$getLatestMigration->execute();
if ($getLatestMigration->rowCount() > 0) {
$getLatestMigration->execute();
$latestMigration = $getLatestMigration->fetch(PDO::FETCH_ASSOC);
return $latestMigration['id'];
}
return -1;
}
private function setupMigrations() {
//Checking if the database already has a migration history
$checkForMigrations = $this->getConnection()->prepare(
file_get_contents(__DIR__ . "/queries/FindMigrationsTable.sql", "utf8")
);
$checkForMigrations->execute();
//If it isn't, then we create it
if ($checkForMigrations->rowCount() < 1) {
$createMigrationsTable = $this->getConnection()->prepare(
file_get_contents(__DIR__ . "/queries/CreateMigrationsTable.sql", "utf8")
);
$createMigrationsTable->execute();
}
}
private function parseMigration($file) {
//Preapring return
$return = [
"up" => "",
"down" => ""
];
//Reading the migration file
$fileFromDisk = file_get_contents($file, "utf8");
$fileFromDisk = explode(PHP_EOL, $fileFromDisk);
//Iterating the file line by line and attempting to find delimiters
$upDelimiter = 0;
$downDelimiter = 0;
$endDelimiter = 0;
foreach ($fileFromDisk as $line => $content) {
if ($content === "UP:") {
$upDelimiter = $line;
continue;
}
if ($content === "DOWN:") {
$downDelimiter = $line;
continue;
}
if ($content === "END_MIGRATION") {
$endDelimiter = $line;
continue;
}
}
//Checking if all delimiters were found
if (!($downDelimiter != 0 && $endDelimiter != 0)) {
throw new Exception("Malformed migration file found at: {$file}");
}
//Extracting the queries
$upQuery = array_slice(
$fileFromDisk,
$upDelimiter + 1, //Start of the "UP:" tag
($downDelimiter - $upDelimiter) - 1 //The ammount of lines between "UP:" and "DOWN:"
);
$downQuery = array_slice(
$fileFromDisk,
$downDelimiter + 1, //Start of the "DOWN:" tag
($endDelimiter - $downDelimiter) - 1 //The ammount of line between "DOWN:" and "END_MIGRATION"
);
//Turning the queries back into strings
$return['UP'] = implode(PHP_EOL, $upQuery);
$return['DOWN'] = implode(PHP_EOL, $downQuery);
return $return;
}
private function parseMigrationMeta($file) {
$fileName = explode(" - ", $file);
$toBeReturned = [
"id" => $fileName[0],
"name" => $fileName[1]
];
return $toBeReturned;
}
}
?>