Jacek Kowalski
2019-06-30 0b6d2f4164b9d823fb2a49d9fb4e83242f695e09
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
<?php
class Database {
    private $pdo;
    private $addStatement;
    
    private $cacheId;
    private $cacheNum;
    
    public function __construct($file) {
        $this->pdo = new PDO('sqlite:'.$file);
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $this->pdo->query('CREATE TABLE IF NOT EXISTS vehicles (
            id INT PRIMARY KEY,
            num INT UNIQUE,
            weight INT
        )');
        
        $this->addStatement = $this->pdo->prepare('INSERT OR REPLACE INTO vehicles (id, num, weight) VALUES (:id, :num, :weight)');
        
        $this->_cacheClear();
    }
    
    public function beginTransaction() {
        $this->pdo->beginTransaction();
    }
    
    public function commit() {
        $this->pdo->commit();
    }
    
    public function rollback() {
        $this->pdo->rollback();
    }
    
    protected function _cachePopulate() {
        if($this->cacheId === NULL) {
            $st = $this->pdo->prepare('SELECT * FROM vehicles');
            $st->execute();
            $result = $st->fetchAll(PDO::FETCH_ASSOC);
            
            $this->cacheId = [];
            $this->cacheNum = [];
            foreach($result as $vehicle) {
                $this->_cacheAdd($vehicle);
            }
        }
    }
    
    protected function _cacheAdd($vehicle) {
        $this->_cachePopulate();
        $this->cacheId[$vehicle['id']] = $vehicle;
        $this->cacheNum[$vehicle['num']] = $vehicle;
    }
    
    protected function _cacheClear() {
        $this->cacheId = NULL;
        $this->cacheNum = NULL;
    }
    
    public function getAll() {
        $this->_cachePopulate();
        return $this->cacheId;
    }
    
    public function getById($id) {
        $this->_cachePopulate();
        return $this->cacheId[$id] ?? NULL;
    }
    
    public function getByNum($num) {
        $this->_cachePopulate();
        return $this->cacheNum[$num] ?? NULL;
    }
    
    public function clear() {
        $this->pdo->query('DELETE FROM vehicles');
        $this->_cacheClear();
    }
    
    public function add($id, $num, $weight) {
        $vehicle = [
            'id' => (string)$id,
            'num' => (string)$num,
            'weight' => (string)$weight
        ];
        $this->addStatement->execute($vehicle);
        $this->_cacheAdd($vehicle);
    }
    
    public function addMapping($mapping) {
        $this->beginTransaction();
        $weight = count($mapping);
        foreach($mapping as $id => $num) {
            $this->add($id, $num, $weight);
        }
        $this->commit();
    }
}