1+ <?php
2+
3+ namespace App \Core \DB ;
4+
5+ use App \Core \Application ;
6+ use PDO ;
7+
8+ class Database
9+ {
10+ public PDO $ pdo ;
11+
12+
13+ public function __construct (array $ config )
14+ {
15+ $ dsn = $ config ['dsn ' ] ?? '' ;
16+ $ user = $ config ['user ' ] ?? '' ;
17+ $ password = $ config ['password ' ] ?? '' ;
18+ $ this ->pdo = new PDO ($ dsn , $ user , $ password );
19+ $ this ->pdo ->setAttribute (PDO ::ATTR_ERRMODE , PDO ::ERRMODE_EXCEPTION );
20+ }
21+
22+ public function applyMigrations ()
23+ {
24+ $ this ->createMigrationsTable ();
25+
26+ $ appliedMigrations = $ this ->getAppliedMigrations ();
27+
28+ $ files = scandir (Application::$ ROOT_DIR . '/migrations ' );
29+
30+ $ toApplyMigrations = array_diff ($ files , $ appliedMigrations );
31+ $ newMigrations = [];
32+
33+ foreach ($ toApplyMigrations as $ migration ) {
34+ if ($ migration === '. ' || $ migration === '.. ' ) {
35+ continue ;
36+ }
37+
38+ require_once Application::$ ROOT_DIR . '/migrations/ ' . $ migration ;
39+
40+ $ className = pathinfo ($ migration , PATHINFO_FILENAME );
41+
42+ $ instance = new $ className ();
43+ $ this ->log ("Applying migration $ migration " );
44+ $ instance ->up ();
45+
46+ $ this ->log ("Applied migration $ migration " );
47+
48+ $ newMigrations [] = $ migration ;
49+ }
50+
51+ if (!empty ($ newMigrations )) {
52+ $ this ->saveMigrations ($ newMigrations );
53+ } else {
54+ $ this ->log ("All Migrations are applied " );
55+ }
56+ }
57+
58+ public function createMigrationsTable ()
59+ {
60+ $ this ->pdo ->exec ("
61+ CREATE TABLE IF NOT EXISTS migrations(
62+ id INT AUTO_INCREMENT PRIMARY KEY,
63+ migration VARCHAR(255),
64+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
65+ )
66+ ENGINE=INNODB;
67+ " );
68+ }
69+
70+ public function getAppliedMigrations ()
71+ {
72+ $ statement = $ this ->pdo ->prepare ("SELECT migration from migrations " );
73+ $ statement ->execute ();
74+
75+ return $ statement ->fetchAll (PDO ::FETCH_COLUMN );
76+ }
77+
78+ protected function log ($ message )
79+ {
80+ echo '[ ' . date ('Y-m-d H:i:s ' ) . '] - ' . $ message . PHP_EOL ;
81+ }
82+
83+ public function saveMigrations (array $ migrations )
84+ {
85+ $ str = implode (", " , array_map (fn ($ migration ) => "(' $ migration') " , $ migrations ));
86+
87+ $ statement = $ this ->pdo ->prepare ("
88+ INSERT INTO migrations (migration) VALUES
89+ $ str
90+ " );
91+
92+ $ statement ->execute ();
93+ }
94+
95+ public function prepare ($ sql )
96+ {
97+ return $ this ->pdo ->prepare ($ sql );
98+ }
99+ }
0 commit comments