DatabaseSelect::updateCache()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 3
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 4
rs 10
1
<?php
2
namespace Maphper\DataSource;
3
4
class DatabaseSelect {
5
    private $resultCache = [];
6
    private $idCache = [];
7
    private $selectBuilder;
8
    private $whereBuilder;
9
    private $adapter;
10
    private $databaseModify;
11
    private $defaultSort;
12
    private $table;
13
14
    public function __construct(DatabaseAdapter $adapter, DatabaseModify $databaseModify, $table, $defaultSort, $cacheMode) {
15
        $this->adapter = $adapter;
16
        $this->databaseModify = $databaseModify;
17
        $this->selectBuilder = new \Maphper\Lib\SelectBuilder();
18
        $this->whereBuilder = new \Maphper\Lib\Sql\WhereBuilder();
19
        $this->defaultSort = $defaultSort;
20
        $this->cacheMode = $cacheMode;
0 ignored issues
show
Bug Best Practice introduced by
The property cacheMode does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
21
        $this->table = $table;
22
    }
23
24
    public function findById($id, $pk) {
25
		if (($this->cacheMode && !isset($this->idCache[$id])) || !$this->cacheMode) {
26
			try {
27
				$result = $this->selectQuery($this->selectBuilder->select($this->table, $pk . ' = :id', [':id' => $id], ['limit' => 1]));
28
			}
29
			catch (\Exception $e) {
30
                // Don't issue an error if it cannot be found since we return null
31
			}
32
33
			if (isset($result[0])) $result = $result[0];
34
			else return null;
35
36
            if (!$this->cacheMode) return $result;
37
            else return $this->idCache[$id] = $result;
38
		}
39
		// cacheMode is true and cache is set
40
        return $this->idCache[$id];
41
	}
42
43
    public function findByField(array $fields, $options = []) {
44
		$cacheId = md5(serialize(func_get_args()));
45
46
    if (($this->cacheMode && !isset($this->resultCache[$cacheId])) || !$this->cacheMode) {
47
			$query = $this->whereBuilder->createSql($fields);
48
49
			if (!isset($options['order'])) $options['order'] = $this->defaultSort;
50
51
			try {
52
				$result = $this->selectQuery($this->selectBuilder->select($this->table, $query['sql'], $query['args'], $options));
53
				$this->databaseModify->addIndex(array_keys($query['args']));
54
				$this->databaseModify->addIndex(explode(',', $options['order']));
55
			}
56
			catch (\Exception $e) {
57
				$this->errors[] = $e;
0 ignored issues
show
Bug Best Practice introduced by
The property errors does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
58
				$result = [];
59
			}
60
		}
61
62
    if ($this->cacheMode) {
63
      if (isset($result)) $this->resultCache[$cacheId] = $result;
64
      if (isset($this->resultCache[$cacheId])) return $this->resultCache[$cacheId];
65
    }
66
67
    return $result;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.
Loading history...
68
	}
69
70
    public function findAggregate($function, $field, $group = null, array $criteria = [], array $options = []) {
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

70
    public function findAggregate($function, $field, $group = null, array $criteria = [], /** @scrutinizer ignore-unused */ array $options = []) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
71
		//Cannot count/sum/max multiple fields, pick the first one. This should only come into play when trying to count() a mapper with multiple primary keys
72
		if (is_array($field)) $field = $field[0];
73
		$query = $this->whereBuilder->createSql($criteria);
74
75
		try {
76
			$this->databaseModify->addIndex(array_keys($query['args']));
77
			$this->databaseModify->addIndex(explode(',', $group));
78
			$result = $this->selectQuery($this->selectBuilder->aggregate($this->table, $function, $field, $query['sql'], $query['args'], $group));
79
80
			return $this->determineAggregateResult($result, $group, $field);
81
		}
82
		catch (\Exception $e) {
83
			return $group ? [] : 0;
84
		}
85
	}
86
87
    private function determineAggregateResult($result, $group, $field) {
88
        if ($group != null) {
89
            $ret = [];
90
            foreach ($result as $res) $ret[$res->$field] = $res->val;
91
            return $ret;
92
        }
93
        else if (isset($result[0])) return $result[0]->val;
94
        else return 0;
95
    }
96
97
    private function selectQuery(\Maphper\Lib\Query $query) {
98
        return $this->adapter->query($query)->fetchAll(\PDO::FETCH_OBJ);
99
    }
100
101
    public function clearResultCache() {
102
        if ($this->cacheMode) $this->resultCache = [];
103
    }
104
105
    public function clearIDCache() {
106
        if ($this->cacheMode) $this->idCache = [];
107
    }
108
109
    public function updateCache($data, $pkValue) {
110
        if ($this->cacheMode) {
111
  		    if (isset($this->cache[$pkValue])) $this->cache[$pkValue] = (object) array_merge((array)$this->cache[$pkValue], (array)$data);
0 ignored issues
show
Bug Best Practice introduced by
The property cache does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
112
  		    else $this->cache[$pkValue] = $data;
113
        }
114
    }
115
116
    public function deleteIDFromCache($id) {
117
        if ($this->cacheMode) unset($this->idCache[$id]);
118
    }
119
}
120