1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Vados\MigrationRunner\command; |
4
|
|
|
|
5
|
|
|
use Phalcon\Db\AdapterInterface; |
6
|
|
|
use Phalcon\Db\Column; |
7
|
|
|
use Phalcon\Di; |
8
|
|
|
use Vados\MigrationRunner\enum\TableName; |
9
|
|
|
use Vados\MigrationRunner\models\TblMigration; |
10
|
|
|
use Vados\MigrationRunner\providers\PathProvider; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class MigrationRun |
14
|
|
|
* @package Vados\MigrationRunner\command |
15
|
|
|
*/ |
16
|
|
|
abstract class MigrationRun |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var AdapterInterface |
20
|
|
|
*/ |
21
|
|
|
private $dbInstance; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* MigrationRun constructor. |
25
|
|
|
*/ |
26
|
|
|
protected function __construct() |
27
|
|
|
{ |
28
|
|
|
$this->dbInstance = Di::getDefault()->getShared('db'); |
29
|
|
|
$this->checkMigrationTable(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
protected function checkMigrationTable() |
33
|
|
|
{ |
34
|
|
|
if (!$this->dbInstance->tableExists(TableName::TBL_MIGRATION)) { |
35
|
|
|
$this->dbInstance->createTable(TableName::TBL_MIGRATION, null, [ |
36
|
|
|
'columns' => [ |
37
|
|
|
new Column('id', [ |
38
|
|
|
'type' => Column::TYPE_INTEGER, |
39
|
|
|
'primary' => true |
40
|
|
|
]), |
41
|
|
|
new Column('migration', [ |
42
|
|
|
'type' => Column::TYPE_TEXT |
43
|
|
|
]) |
44
|
|
|
] |
45
|
|
|
]); |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @return array |
51
|
|
|
*/ |
52
|
|
|
protected function getAppliedMigrations(): array |
53
|
|
|
{ |
54
|
|
|
$migrations = []; |
55
|
|
|
foreach (TblMigration::find() as $item) { |
56
|
|
|
/** @var TblMigration $item */ |
57
|
|
|
$migrations[] = $item->getMigration(); |
58
|
|
|
} |
59
|
|
|
return $migrations; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return array |
64
|
|
|
*/ |
65
|
|
|
protected function getExistingMigrations(): array |
66
|
|
|
{ |
67
|
|
|
if (!is_dir(PathProvider::getMigrationDir())) { |
68
|
|
|
return []; |
69
|
|
|
} |
70
|
|
|
$migrations = scandir(PathProvider::getMigrationDir()); |
71
|
|
|
$ignore = ['.', '..']; |
72
|
|
|
return array_filter($migrations, function($item) use ($ignore) { |
73
|
|
|
return !in_array($item, $ignore); |
74
|
|
|
}); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @return array |
79
|
|
|
*/ |
80
|
|
|
protected function getNewMigrations(): array |
81
|
|
|
{ |
82
|
|
|
$migrations = array_diff($this->getExistingMigrations(), $this->getAppliedMigrations()); |
83
|
|
|
sort($migrations); |
84
|
|
|
return $migrations; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* @param string $text |
89
|
|
|
* @return bool |
90
|
|
|
*/ |
91
|
|
|
protected function actionConfirmation(string $text): bool |
92
|
|
|
{ |
93
|
|
|
echo "$text (yes|no) [yes]: "; |
94
|
|
|
$answer = trim(fgets(STDIN)); |
95
|
|
|
if (!$answer) { |
96
|
|
|
$answer = 'yes'; |
97
|
|
|
} |
98
|
|
|
return !strncasecmp($answer, 'y', 1); |
99
|
|
|
} |
100
|
|
|
} |