Completed
Push — master ( 4a27b3...d9b2e3 )
by Mehmet
05:35
created

Model::create()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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