-
Notifications
You must be signed in to change notification settings - Fork 3
/
Snapshotter.php
97 lines (77 loc) · 2.89 KB
/
Snapshotter.php
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
<?php
namespace Formapro\Yadm\Bundle;
use Formapro\Yadm\Storage;
use MongoDB\Client;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
class Snapshotter
{
/**
* @var Client
*/
private $client;
/**
* @param Client $client
*/
public function __construct(Client $client)
{
$this->client = $client;
}
public function make(Storage $storage, LoggerInterface $logger = null)
{
$logger = $logger ?: new NullLogger();
$collection = $storage->getCollection();
$collectionName = $collection->getCollectionName();
$dbName = $collection->getDatabaseName();
$snapshotDbName = $dbName.'_snapshot';
$this->client->selectCollection($snapshotDbName, $collectionName)->drop();
$logger->debug(sprintf(
'Copy documents from <info>%s.%s</info> to <info>%s.%s</info>',
$dbName,
$collectionName,
$snapshotDbName,
$collectionName
));
$snapshotCollection = $this->client->selectCollection($snapshotDbName, $collectionName);
if ($documents = $collection->find()->toArray()) {
$snapshotCollection->insertMany($documents);
}
}
public function delete(Storage $storage, LoggerInterface $logger = null): void
{
$logger = $logger ?: new NullLogger();
$collection = $storage->getCollection();
$collectionName = $collection->getCollectionName();
$dbName = $collection->getDatabaseName();
$collectionOptions = $storage->getMeta()->getCreateCollectionOptions();
if (array_key_exists('capped', $collectionOptions) && $collectionOptions['capped']) {
$collection->drop();
$this->client->selectDatabase($dbName)->createCollection($collectionName, $storage->getMeta()->getCreateCollectionOptions());
foreach ($storage->getMeta()->getIndexes() as $index) {
$collection->createIndex($index->getKey(), $index->getOptions());
}
} else {
$collection->deleteMany([]);
}
}
public function restore(Storage $storage, LoggerInterface $logger = null)
{
$logger = $logger ?: new NullLogger();
$collection = $storage->getCollection();
$collectionName = $collection->getCollectionName();
$dbName = $collection->getDatabaseName();
$snapshotDbName = $dbName.'_snapshot';
$this->delete($storage, $logger);
$logger->debug(sprintf(
'Copy documents from <info>%s.%s</info> to <info>%s.%s</info>',
$dbName,
$collectionName,
$snapshotDbName,
$collectionName
));
$snapshotCollection = $this->client->selectCollection($snapshotDbName, $collectionName);
if ($documents = $snapshotCollection->find()->toArray()) {
$collection->insertMany($documents);
}
}
}