Passed
Push — master ( 2d27c8...269005 )
by Richard
01:38
created

DatabaseSelect::selectQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 2
rs 10
1
<?php
2
namespace Maphper\DataSource;
3
4
class DatabaseSelect {
5
    private $resultCache = [];
6
    private $selectBuilder;
7
    private $whereBuilder;
8
    private $adapter;
9
    private $databaseModify;
10
    private $defaultSort;
11
    private $table;
12
13
    public function __construct(DatabaseAdapter $adapter, DatabaseModify $databaseModify,  $defaultSort, $table) {
14
        $this->adapter = $adapter;
15
        $this->databaseModify = $databaseModify;
16
        $this->selectBuilder = new \Maphper\Lib\SelectBuilder();
17
        $this->whereBuilder = new \Maphper\Lib\Sql\WhereBuilder();
18
        $this->defaultSort = $defaultSort;
19
        $this->table = $table;
20
    }
21
22
    public function findByField(array $fields, $options = []) {
23
		$cacheId = md5(serialize(func_get_args()));
24
		if (!isset($this->resultCache[$cacheId])) {
25
			$query = $this->whereBuilder->createSql($fields);
26
27
			if (!isset($options['order'])) $options['order'] = $this->defaultSort;
28
29
			try {
30
				$this->resultCache[$cacheId] = $this->selectQuery($this->selectBuilder->select($this->table, $query['sql'], $query['args'], $options));
31
				$this->databaseModify->addIndex(array_keys($query['args']));
32
				$this->databaseModify->addIndex(explode(',', $options['order']));
33
			}
34
			catch (\Exception $e) {
35
				$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...
36
				$this->resultCache[$cacheId] = [];
37
			}
38
		}
39
		return $this->resultCache[$cacheId];
40
	}
41
42
    private function selectQuery(\Maphper\Lib\Query $query) {
43
        return $this->adapter->query($query)->fetchAll(\PDO::FETCH_OBJ);
44
    }
45
46
    public function clearResultCache() {
47
        $this->resultCache = [];
48
    }
49
}
50