1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Pmurkin\MongoSchemaDumper\Console; |
4
|
|
|
|
5
|
|
|
use Illuminate\Console\Command; |
6
|
|
|
use Illuminate\Support\Facades\DB; |
7
|
|
|
|
8
|
|
|
class SchemaImport extends Command |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* The name and signature of the console command. |
12
|
|
|
* |
13
|
|
|
* @var string |
14
|
|
|
*/ |
15
|
|
|
protected $signature = 'schema:import {--file=./schema.json : file with schema}'; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* The console command description. |
19
|
|
|
* |
20
|
|
|
* @var string |
21
|
|
|
*/ |
22
|
|
|
protected $description = 'Import schemas mongo databases from file'; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* SchemaImport constructor. |
26
|
|
|
*/ |
27
|
|
|
public function __construct() |
28
|
|
|
{ |
29
|
|
|
parent::__construct(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Execute the console command. |
34
|
|
|
* |
35
|
|
|
* @return void |
36
|
|
|
*/ |
37
|
|
|
public function handle() |
38
|
|
|
{ |
39
|
|
|
$file = $this->option('file'); |
40
|
|
|
|
41
|
|
|
if (!file_exists($file)) { |
42
|
|
|
$this->warn('File not found'); |
43
|
|
|
return; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$json = file_get_contents($file); |
47
|
|
|
$databases = json_decode($json, true); |
48
|
|
|
foreach ($databases as $database => $collections) { |
49
|
|
|
$this->info('Import: '.$database); |
50
|
|
|
$db = DB::getMongoClient()->selectDatabase($database); |
51
|
|
|
|
52
|
|
|
foreach ($collections as $name => $collection) { |
53
|
|
|
$this->info('Create: '.$name); |
54
|
|
|
$db->createCollection($name, $collection['options']); |
55
|
|
|
|
56
|
|
|
if (isset($collection['indexes']) && !empty($collection['indexes'])) { |
57
|
|
|
$db->selectCollection($name)->createIndexes($collection['indexes']); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
if (isset($collection['data']) && !empty($collection['data'])) { |
61
|
|
|
$db->selectCollection($name)->insertMany($collection['data']); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$this->info('Import is done'); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|