|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace ModelUtils; |
|
4
|
|
|
|
|
5
|
|
|
class Model |
|
6
|
|
|
{ |
|
7
|
|
|
|
|
8
|
|
|
public $config_yaml = ""; |
|
9
|
|
|
public $schema = []; |
|
10
|
|
|
public $type = "basic"; // Possible options are basic, cache, search |
|
11
|
|
|
public $collection_name = ""; |
|
12
|
|
|
public $data_file = null; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct() |
|
15
|
|
|
{ |
|
16
|
|
|
$config = yaml_parse(trim($this->config_yaml)); |
|
17
|
|
|
$this->schema = $config['schema']; |
|
18
|
|
|
$this->collection_name = $config['collection_name']; |
|
19
|
|
|
$this->type = (isset($config['type'])) ? $config['type'] : "basic"; |
|
20
|
|
|
$this->data_file = (isset($config['data_file'])) ? $config['data_file'] : null; |
|
21
|
|
|
|
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
public function validate($doc) |
|
25
|
|
|
{ |
|
26
|
|
|
return ModelUtils::validateDoc($this->schema, $doc); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function setDefaults($doc) |
|
30
|
|
|
{ |
|
31
|
|
|
return ModelUtils::settingModelDefaults($this->schema, $doc); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
|
|
35
|
|
|
public function fitDoc($doc) |
|
36
|
|
|
{ |
|
37
|
|
|
return ModelUtils::fitDocToModel($this->schema, $doc); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function install($db) |
|
41
|
|
|
{ |
|
42
|
|
|
|
|
43
|
|
|
$db->drop($this->collection_name, $this->schema); |
|
44
|
|
|
$db->create($this->collection_name, $this->schema); |
|
45
|
|
|
$indexes = []; |
|
46
|
|
|
foreach ($this->schema as $field => $fconfig) { |
|
47
|
|
|
if ($fconfig['_index'] === true) { |
|
48
|
|
|
$index = ['key'=>[$field=>1]]; |
|
49
|
|
|
if (isset($fconfig["_index_type"])) { |
|
50
|
|
|
switch ($fconfig["_index_type"]) { |
|
51
|
|
|
case 'unique': |
|
52
|
|
|
$index['unique'] = true; |
|
53
|
|
|
break; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
$indexes[] = $index; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
if ($this->data_file !== null) { |
|
60
|
|
|
if (file_exists(BASE_DIR.$this->data_file)) { |
|
61
|
|
|
$data = json_decode(file_get_contents(BASE_DIR.$this->data_file), true); |
|
62
|
|
|
foreach ($data as $item) { |
|
63
|
|
|
$item = ModelUtils::settingModelDefaults($this->schema, $item); |
|
64
|
|
|
$doc = ModelUtils::validateDoc($this->schema, $item); |
|
65
|
|
|
$db->insert($this->collection_name, $doc); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
if (count($indexes)>0) { |
|
70
|
|
|
$db->createIndexes($this->collection_name, $indexes); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|