1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Console\Traits; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Capsule\Manager as Capsule; |
6
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
7
|
|
|
use Symfony\Component\Finder\Finder; |
8
|
|
|
|
9
|
|
|
trait DbHelper |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Return class name by file basename |
13
|
|
|
* @param string $baseName |
14
|
|
|
* |
15
|
|
|
* @return string |
16
|
|
|
*/ |
17
|
|
|
private function getClassName($baseName) |
18
|
|
|
{ |
19
|
|
|
$filenameParts = explode('_', $baseName); |
20
|
|
|
$class = ''; |
21
|
|
|
|
22
|
|
|
array_shift($filenameParts); |
23
|
|
|
|
24
|
|
|
foreach ($filenameParts as $key => $filenamePart) { |
25
|
|
|
$class .= ucfirst($filenamePart); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
return $class; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param string $tableName |
33
|
|
|
*/ |
34
|
|
|
private function safeCreateTable($tableName) |
35
|
|
|
{ |
36
|
|
|
if (!Capsule::schema()->hasTable($tableName)) { |
37
|
|
|
Capsule::schema()->create($tableName, function($table) { |
38
|
|
|
$table->string('version'); |
39
|
|
|
$table->timestamp('apply_time')->useCurrent(); |
40
|
|
|
$table->primary('version'); |
41
|
|
|
}); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param $name |
47
|
|
|
* @param $table |
48
|
|
|
* @return bool |
49
|
|
|
*/ |
50
|
|
|
private function isRowExist($name, $table) |
51
|
|
|
{ |
52
|
|
|
$item = Capsule::table($table)->where('version', $name)->first(); |
53
|
|
|
return !is_null($item); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param $name |
58
|
|
|
* @param $table |
59
|
|
|
*/ |
60
|
|
|
private function insertRow($name, $table) |
61
|
|
|
{ |
62
|
|
|
Capsule::table($table)->insert([ |
63
|
|
|
'version' => $name, |
64
|
|
|
]); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Run list of commands in files |
69
|
|
|
* |
70
|
|
|
* @param Finder $files list of files to run |
71
|
|
|
* @param OutputInterface $output |
72
|
|
|
* @param string $tableName |
73
|
|
|
* @param string $method |
74
|
|
|
* |
75
|
|
|
* @return void |
76
|
|
|
*/ |
77
|
|
|
private function runActions(Finder $files, OutputInterface $output, $tableName, $method) |
78
|
|
|
{ |
79
|
|
|
foreach ($files as $file) { |
80
|
|
|
$baseName = $file->getBasename('.php'); |
81
|
|
|
$class = $this->getClassName($baseName); |
82
|
|
|
|
83
|
|
|
if ($this->isRowExist($baseName, $tableName)) { |
84
|
|
|
$output->writeln([sprintf('`%s` - already exists.', $baseName)]); |
85
|
|
|
continue; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
require_once($file); |
89
|
|
|
|
90
|
|
|
$obj = new $class(); |
91
|
|
|
$obj->$method(); |
92
|
|
|
|
93
|
|
|
$this->insertRow($baseName, $tableName); |
94
|
|
|
$output->writeln([sprintf('`%s` - done.', $baseName)]); |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
$output->writeln(['<info>Completed.</info>']); |
98
|
|
|
|
99
|
|
|
return; |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|