-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathArrayQuery.php
146 lines (122 loc) · 2.7 KB
/
ArrayQuery.php
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
<?php
namespace yii2mod\query;
use Yii;
use yii\base\Component;
use yii\db\QueryTrait;
/**
* Class ArrayQuery
*
* @package yii2mod\query
*/
class ArrayQuery extends Component
{
use QueryTrait;
/**
* @var string name of the data key, which should be used as row unique id - primary key
*/
public $primaryKeyName = 'id';
/**
* @var array the data to search, filter
*/
public $from;
/**
* @var string the class for processing the queries
*/
public $queryProcessorClass = 'yii2mod\query\QueryProcessor';
/**
* @var QueryProcessor
*/
private $_queryProcessor;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->_queryProcessor = Yii::createObject($this->queryProcessorClass);
}
/**
* Executes the query and returns all results as an array.
*
* @return array
*/
public function all(): array
{
$rows = $this->fetchData();
return $this->populate($rows);
}
/**
* Executes the query and returns a single row of result.
*
* @return bool|mixed
*/
public function one()
{
$rows = $this->fetchData();
return empty($rows) ? false : reset($rows);
}
/**
* Returns the number of records.
*
* @return int
*/
public function count(): int
{
$data = $this->fetchData();
return count($data);
}
/**
* Returns a value indicating whether the query result contains any row of data.
*
* @return bool
*/
public function exists(): bool
{
$data = $this->fetchData();
return !empty($data);
}
/**
* Sets data to be selected from.
*
* @param array $data
*
* @return $this
*/
public function from(array $data)
{
$this->from = $data;
return $this;
}
/**
* Fetches data.
*
* @return array
*/
protected function fetchData(): array
{
return $this->_queryProcessor->process($this);
}
/**
* Converts the raw query results into the format as specified by this query.
*
* @param $rows
*
* @return array
*/
public function populate($rows): array
{
$result = [];
if ($this->indexBy === null) {
return array_values($rows); // reset storage internal keys
}
foreach ($rows as $row) {
if (is_string($this->indexBy)) {
$key = $row[$this->indexBy];
} else {
$key = call_user_func($this->indexBy, $row);
}
$result[$key] = $row;
}
return $result;
}
}