1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Component\Migration; |
4
|
|
|
|
5
|
|
|
use App\Component\Model\Orm\Orm; |
6
|
|
|
use App\Component\Db\Migration; |
7
|
|
|
use App\Model\Accounts; |
8
|
|
|
use App\Model\Repository\Users as UsersRepository; |
9
|
|
|
use Nymfonya\Component\Container; |
10
|
|
|
|
11
|
|
|
class Users extends Migration |
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* repository |
16
|
|
|
* |
17
|
|
|
* @var Orm |
18
|
|
|
*/ |
19
|
|
|
protected $repository; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Undocumented function |
23
|
|
|
* |
24
|
|
|
* @param Container $container |
25
|
|
|
*/ |
26
|
4 |
|
public function __construct(Container $container) |
27
|
|
|
{ |
28
|
4 |
|
parent::__construct($container); |
29
|
4 |
|
$this->repository = new UsersRepository($container); |
30
|
4 |
|
$this->fromOrm($this->repository); |
31
|
4 |
|
$this->migrate(); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* check if migration can run |
36
|
|
|
* |
37
|
|
|
* @return boolean |
38
|
|
|
*/ |
39
|
1 |
|
protected function canMigrate(): bool |
40
|
|
|
{ |
41
|
1 |
|
$sql = 'SHOW TABLES LIKE ' . $this->repository->getTable(); |
42
|
1 |
|
$this->run($sql)->hydrate(); |
43
|
1 |
|
$result = $this->getRowset(); |
44
|
1 |
|
return (count($result) == 0); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* sql to create table |
49
|
|
|
* |
50
|
|
|
* @return Migration |
51
|
|
|
*/ |
52
|
1 |
|
protected function runCreate(): Migration |
53
|
|
|
{ |
54
|
1 |
|
$sql = "CREATE TABLE `users` ( |
55
|
|
|
`id` bigint(20) NOT NULL AUTO_INCREMENT, |
56
|
|
|
`name` varchar(255) NOT NULL, |
57
|
|
|
`email` varchar(255) NOT NULL, |
58
|
|
|
`password` varchar(255) NOT NULL, |
59
|
|
|
`status` varchar(255) NOT NULL, |
60
|
|
|
`role` varchar(255) NOT NULL, |
61
|
|
|
UNIQUE KEY `id` (`id`), |
62
|
|
|
KEY `email` (`email`) |
63
|
|
|
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;"; |
64
|
1 |
|
$this->run($sql); |
65
|
1 |
|
return $this; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* sql to insert into table |
70
|
|
|
* |
71
|
|
|
* @return Migration |
72
|
|
|
*/ |
73
|
1 |
|
protected function runInsert(): Migration |
74
|
|
|
{ |
75
|
1 |
|
if (false === $this->isError()) { |
76
|
|
|
$csvArray = (new Accounts($this->container))->toArray(); |
77
|
|
|
$fields = [ |
78
|
|
|
'id', 'name', 'email', 'password', 'status', 'role' |
79
|
|
|
]; |
80
|
|
|
$insertDatas = array_map(function ($values) use ($fields) { |
81
|
|
|
return array_combine($fields, $values); |
82
|
|
|
}, $csvArray); |
83
|
|
|
foreach ($insertDatas as $data) { |
84
|
|
|
$this->repository->resetBuilder(); |
85
|
|
|
|
86
|
|
|
$this->repository->insert($data); |
87
|
|
|
$this->run( |
88
|
|
|
$this->repository->getSql(), |
89
|
|
|
$this->repository->getBuilderValues() |
90
|
|
|
); |
91
|
|
|
} |
92
|
|
|
} |
93
|
1 |
|
return $this; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|