|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @author Sergii Bondarenko, <[email protected]> |
|
4
|
|
|
*/ |
|
5
|
|
|
namespace Drupal\TqExtension\Utils\Database; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class Database. |
|
9
|
|
|
* |
|
10
|
|
|
* @package Drupal\TqExtension\Utils\Database |
|
11
|
|
|
*/ |
|
12
|
|
|
class Database |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var Operator |
|
16
|
|
|
*/ |
|
17
|
|
|
private $db; |
|
18
|
|
|
/** |
|
19
|
|
|
* Name of original database. |
|
20
|
|
|
* |
|
21
|
|
|
* @var string |
|
22
|
|
|
*/ |
|
23
|
|
|
private $source = ''; |
|
24
|
|
|
/** |
|
25
|
|
|
* Name of temporary database that will store data from original. |
|
26
|
|
|
* |
|
27
|
|
|
* @var string |
|
28
|
|
|
*/ |
|
29
|
|
|
private $temporary = ''; |
|
30
|
|
|
/** |
|
31
|
|
|
* Indicates that DB was cloned. |
|
32
|
|
|
* |
|
33
|
|
|
* @var bool |
|
34
|
|
|
*/ |
|
35
|
|
|
private $cloned = false; |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @param string $connection |
|
39
|
|
|
* Database connection name (key in $databases array from settings.php). |
|
40
|
|
|
*/ |
|
41
|
|
|
public function __construct($connection) |
|
42
|
|
|
{ |
|
43
|
|
|
if (!defined('DRUPAL_ROOT') || !function_exists('conf_path')) { |
|
44
|
|
|
throw new \RuntimeException('Drupal is not bootstrapped.'); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
$databases = []; |
|
48
|
|
|
|
|
49
|
|
|
require sprintf('%s/%s/settings.php', DRUPAL_ROOT, conf_path()); |
|
50
|
|
|
|
|
51
|
|
|
if (empty($databases[$connection])) { |
|
52
|
|
|
throw new \InvalidArgumentException(sprintf('The "%s" database connection does not exist.', $connection)); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$db = $databases[$connection]['default']; |
|
56
|
|
|
|
|
57
|
|
|
$this->db = new Operator($db['username'], $db['password'], $db['host'], $db['port']); |
|
58
|
|
|
$this->source = $db['database']; |
|
59
|
|
|
$this->temporary = "tqextension_$this->source"; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* Clone a database. |
|
64
|
|
|
*/ |
|
65
|
|
|
public function __clone() |
|
66
|
|
|
{ |
|
67
|
|
|
// Drop and create temporary DB and copy source into it. |
|
68
|
|
|
$this->db->copy($this->source, $this->temporary); |
|
69
|
|
|
$this->cloned = true; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* Restore original database. |
|
74
|
|
|
*/ |
|
75
|
|
|
public function __destruct() |
|
76
|
|
|
{ |
|
77
|
|
|
if ($this->cloned) { |
|
78
|
|
|
// Drop and create source DB and copy temporary into it. |
|
79
|
|
|
$this->db->copy($this->temporary, $this->source); |
|
80
|
|
|
// Kill temporary DB. |
|
81
|
|
|
$this->db->drop($this->temporary); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|