forked from Codeception/module-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMongoDb.php
More file actions
249 lines (216 loc) · 6.63 KB
/
MongoDb.php
File metadata and controls
249 lines (216 loc) · 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
<?php
declare(strict_types=1);
namespace Codeception\Lib\Driver;
use Codeception\Exception\ModuleConfigException;
use Codeception\Exception\ModuleException;
use Exception;
use MongoDB\Client;
use MongoDB\Database;
use MongoDB\Driver\Exception\Exception as MongoDbDriverException;
class MongoDb
{
/**
* @var int
*/
public const DEFAULT_PORT = 27017;
private ?Client $client;
private Database $dbh;
private ?string $dbName;
private string $host;
private string $user;
private string $password;
private string $quiet = '';
/**
* Connect to the Mongo server using the MongoDB extension.
*/
protected function setupMongoDB(string $dsn, array $options): void
{
try {
$this->client = new Client($dsn, $options);
$this->dbh = $this->client->selectDatabase($this->dbName);
} catch (MongoDbDriverException $e) {
throw new ModuleException($this, sprintf('Failed to open Mongo connection: %s', $e->getMessage()));
}
}
/**
* Clean up the Mongo database using the MongoDB extension.
*/
protected function cleanupMongoDB(): void
{
try {
$this->dbh->drop();
} catch (MongoDbDriverException $e) {
throw new Exception(sprintf('Failed to drop the DB: %s', $e->getMessage()), $e->getCode(), $e);
}
}
/**
* $dsn has to contain db_name after the host. E.g. "mongodb://localhost:27017/mongo_test_db"
*
* @static
*
* @throws ModuleConfigException
* @throws Exception
*/
public function __construct(string $dsn, string $user, string $password)
{
/* defining DB name */
$this->dbName = preg_replace('#\?.*#', '', substr($dsn, strrpos($dsn, '/') + 1));
if (strlen($this->dbName) == 0) {
throw new ModuleConfigException($this, 'Please specify valid $dsn with DB name after the host:port');
}
/* defining host */
if (str_starts_with($dsn, 'mongodb://')) {
$this->host = str_replace('mongodb://', '', preg_replace('#\?.*#', '', $dsn));
} else {
$this->host = $dsn;
}
$this->host = rtrim(str_replace($this->dbName, '', $this->host), '/');
$options = [
'connect' => true
];
if ($user && $password) {
$options += [
'username' => $user,
'password' => $password
];
}
$this->setupMongoDB($dsn, $options);
$this->user = $user;
$this->password = $password;
}
/**
* @static
*/
public static function create(string $dsn, string $user, string $password): \Codeception\Lib\Driver\MongoDb
{
return new MongoDb($dsn, $user, $password);
}
public function cleanup(): void
{
$this->cleanupMongoDB();
}
/**
* dump file has to be a javascript document where one can use all the mongo shell's commands
* just FYI: this file can be easily created be RockMongo's export button
*/
public function load(string $dumpFile): void
{
$shell = $this->findMongoShellBinary();
$uri = $this->host . '/' . $this->dbName;
$cmd = sprintf(
'%s %s %s%s',
$shell,
$uri,
$this->createUserPasswordCmdString(),
escapeshellarg($dumpFile)
);
shell_exec($cmd);
}
private function findMongoShellBinary(): string
{
if ($this->commandExists('mongo')) {
return 'mongo';
}
if ($this->commandExists('mongosh')) {
return 'mongosh';
}
throw new ModuleException($this, 'Neither mongosh nor mongo found in PATH.');
}
private function commandExists(string $cmd): bool
{
$null = PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null';
exec(
sprintf('%s --version > %s 2>&1', escapeshellcmd($cmd), $null),
$_,
$code
);
return $code === 0;
}
public function loadFromMongoDump(string $dumpFile): void
{
[$host, $port] = $this->getHostPort();
$cmd = sprintf(
"mongorestore %s --host %s --port %s -d %s %s %s",
$this->quiet,
$host,
$port,
$this->dbName,
$this->createUserPasswordCmdString(),
escapeshellarg($dumpFile)
);
shell_exec($cmd);
}
public function loadFromTarGzMongoDump(string $dumpFile): void
{
[$host, $port] = $this->getHostPort();
$getDirCmd = sprintf(
"tar -tf %s | awk 'BEGIN { FS = \"/\" } ; { print $1 }' | uniq",
escapeshellarg($dumpFile)
);
$dirCountCmd = $getDirCmd . ' | wc -l';
if (trim(shell_exec($dirCountCmd)) !== '1') {
throw new ModuleException(
$this,
'Archive MUST contain single directory with db dump'
);
}
$dirName = trim(shell_exec($getDirCmd));
$cmd = sprintf(
'tar -xzf %s && mongorestore %s --host %s --port %s -d %s %s %s && rm -r %s',
escapeshellarg($dumpFile),
$this->quiet,
$host,
$port,
$this->dbName,
$this->createUserPasswordCmdString(),
$dirName,
$dirName
);
shell_exec($cmd);
}
private function createUserPasswordCmdString(): string
{
if ($this->user && $this->password) {
return sprintf(
'--username %s --password %s ',
$this->user,
$this->password
);
}
return '';
}
public function getDbh(): Database
{
return $this->dbh;
}
public function setDatabase(string $dbName): void
{
$this->dbh = $this->client->selectDatabase($dbName);
}
public function getDbHash(): ?string
{
$result = $this->dbh->command(['dbHash' => 1]);
if (!is_array($result)) {
$result = iterator_to_array($result);
}
return $result[0]->md5 ?? null;
}
/**
* @return array<string|int>
*/
private function getHostPort(): array
{
$hostPort = explode(':', $this->host);
if (count($hostPort) === 2) {
return $hostPort;
}
if (count($hostPort) === 1) {
return [$hostPort[0], self::DEFAULT_PORT];
}
throw new ModuleException($this, '$dsn MUST be like (mongodb://)<host>:<port>/<db name>');
}
public function setQuiet(bool $quiet): void
{
$this->quiet = $quiet ? '--quiet' : '';
}
}