-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigration.php
107 lines (89 loc) · 3.14 KB
/
migration.php
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
<?php
#Pass arugumet as rollback for rollback or else to run migration pass run or none.
#Mind the migrations directory and class name and file names
include __DIR__ . '/settings.php';
class migration
{
protected $connection;
private $ranMigrations = [];
private $lastBatch = [];
private $batch_id = 1;
public function __construct($type = "")
{
$this->setConnection();
$this->setRanMigrations();
$this->runMigration($type);
}
public function __destruct()
{
$this->connection->close();
}
protected function setConnection()
{
$this->connection = new mysqli(SERVERNAME, USER, PASSWORD, DBNAME);
if ($this->connection->connect_error)
error_log("Connection failed: " . $this->connection->connect_error);
}
protected function setRanMigrations()
{
$result = $this->connection->query("SELECT * FROM migration");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$this->ranMigrations[] = $row['name'];
$this->lastBatch[$row['batch_id']][] = $row['name'];
if ($this->batch_id < $row['batch_id']) $this->batch_id = $row['batch_id'];
}
}
$this->lastBatch = $this->lastBatch[$this->batch_id];
print_r($this->lastBatch);
}
private function migrate()
{
$Query = "";
foreach (glob(DOCUMENT_ROOT . '/migrations/*.php') as $file) {
if (!in_array(basename($file, ".php"), $this->ranMigrations)) {
$class = "migrations\\" . basename($file, ".php");
$this->runQuery($class::UP);
$Query .= "INSERT INTO migration (name , batch_id) VALUES ( '" . basename($file, ".php") . "' , " . ($this->batch_id + 1) . " );";
}
}
return $this->connection->multi_query($Query);
}
private function rollbackMigrations()
{
foreach ($this->lastBatch as $migration) {
$class = "migrations\\" . $migration;
$this->runQuery($class::DOWN);
}
return $this->runQuery("DELETE FROM migration WHERE batch_id =" . $this->batch_id . ";");
}
protected function runQuery($sql = "")
{
try {
if ($this->connection->query($sql) === TRUE) {
return true;
} else {
echo "Error: " . $sql . "<br>" . $this->connection->error;
return false;
}
} catch (Exception $e) {
error_log("Exception: " . $e->getMessage());
}
}
protected function runMigration($type = "")
{
if ($type == "" || $type == 'run') {
if ($this->migrate() === TRUE)
echo "Migration Ran successfully";
else
echo "Error:" . $this->connection->error;
} else if ($type == 'rollback') {
if ($this->rollbackMigrations() === TRUE)
echo "Rollbacked Last Migration successfully";
else
echo "Error:" . $this->connection->error;
}
}
}
$type = !empty($argv[1]) ? $argv[1] : "";
new migration($type);