1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace PmgDev\DatabaseReplicator; |
4
|
|
|
|
5
|
|
|
use PmgDev\DatabaseReplicator\Database\Replicator; |
6
|
|
|
use PmgDev\DatabaseReplicator\Exceptions\InvalidStateException; |
7
|
|
|
|
8
|
|
|
abstract class Database implements DatabaseConnection |
9
|
|
|
{ |
10
|
|
|
/** @var Replicator */ |
11
|
|
|
private $replicator; |
12
|
|
|
|
13
|
|
|
/** @var Config|NULL */ |
14
|
|
|
private $config; |
15
|
|
|
|
16
|
|
|
/** @var object|NULL */ |
17
|
|
|
private $connection; |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
public function __construct(Replicator $replicator) |
21
|
|
|
{ |
22
|
|
|
$this->replicator = $replicator; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
|
26
|
|
|
public function create()/*: object php 7.2+*/ |
27
|
|
|
{ |
28
|
|
|
$this->config = $this->createDatabase(); |
29
|
|
|
$this->connection = $this->createConnection($this->config); |
30
|
|
|
return $this->connection; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
|
34
|
|
|
public function drop(): void |
35
|
|
|
{ |
36
|
|
|
$this->disconnectConnection($this->getConnection()); |
37
|
|
|
$this->dropDatabase($this->getConfig()); |
38
|
|
|
$this->connection = NULL; |
39
|
|
|
$this->config = NULL; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
public function getConnection()/*: object php 7.2+*/ |
44
|
|
|
{ |
45
|
|
|
if ($this->connection === NULL) { |
46
|
|
|
throw new InvalidStateException('Connection does not exists, you must call create() method first.'); |
47
|
|
|
} |
48
|
|
|
return $this->connection; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
|
52
|
|
|
protected function dropDatabase(Config $config): void |
53
|
|
|
{ |
54
|
|
|
$this->replicator->drop($config->database); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
|
58
|
|
|
protected function createDatabase(): Config |
59
|
|
|
{ |
60
|
|
|
return $this->replicator->copy(); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
|
64
|
|
|
final protected function getConfig(): Config |
65
|
|
|
{ |
66
|
|
|
if ($this->config === NULL) { |
67
|
|
|
throw new InvalidStateException('Config does not exists, you must call create() method first.'); |
68
|
|
|
} |
69
|
|
|
return $this->config; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
|
73
|
|
|
abstract protected function createConnection(Config $config)/*: object php 7.2+*/; |
74
|
|
|
|
75
|
|
|
|
76
|
|
|
abstract protected function disconnectConnection(/*: object php 7.2+*/ $connection): void; |
77
|
|
|
|
78
|
|
|
} |
79
|
|
|
|