1+ <?php
2+
3+ namespace yii2mod \query ;
4+
5+ use Yii ;
6+ use yii \base \Component ;
7+ use yii \db \QueryTrait ;
8+
9+ class ArrayQuery extends Component
10+ {
11+ use QueryTrait;
12+
13+ /**
14+ * @var string name of the data key, which should be used as row unique id - primary key.
15+ */
16+ public $ primaryKeyName = 'id ' ;
17+
18+ /**
19+ * @var array the data to search, filter.
20+ */
21+ public $ from ;
22+
23+ /**
24+ * @var string the class for processing the queries
25+ */
26+ public $ queryProcessorClass = 'app\components\QueryProcessor ' ;
27+
28+ /**
29+ * @var QueryProcessor
30+ */
31+ protected $ queryProcessor ;
32+
33+ /**
34+ * @inheritdoc
35+ */
36+ public function init ()
37+ {
38+ $ this ->queryProcessor = Yii::createObject ($ this ->queryProcessorClass );
39+
40+ parent ::init ();
41+ }
42+
43+ /**
44+ * Executes the query and returns all results as an array.
45+ *
46+ * @return array
47+ */
48+ public function all ()
49+ {
50+ $ rows = $ this ->fetchData ();
51+
52+ return $ this ->populate ($ rows );
53+ }
54+
55+ /**
56+ * Executes the query and returns a single row of result.
57+ *
58+ * @return bool|mixed
59+ */
60+ public function one ()
61+ {
62+ $ rows = $ this ->fetchData ();
63+
64+ return empty ($ rows ) ? false : reset ($ rows );
65+ }
66+
67+ /**
68+ * Returns the number of records.
69+ *
70+ * @return int
71+ */
72+ public function count ()
73+ {
74+ $ data = $ this ->fetchData ();
75+
76+ return count ($ data );
77+ }
78+
79+ /**
80+ * Returns a value indicating whether the query result contains any row of data.
81+ *
82+ * @return bool
83+ */
84+ public function exists ()
85+ {
86+ $ data = $ this ->fetchData ();
87+
88+ return !empty ($ data );
89+ }
90+
91+ /**
92+ * Sets data to be selected from.
93+ *
94+ * @param array $data
95+ * @return $this
96+ */
97+ public function from (array $ data )
98+ {
99+ $ this ->from = $ data ;
100+
101+ return $ this ;
102+ }
103+
104+ /**
105+ * Fetches data.
106+ *
107+ * @return mixed
108+ */
109+ protected function fetchData ()
110+ {
111+ return $ this ->queryProcessor ->process ($ this );
112+ }
113+
114+ /**
115+ * Converts the raw query results into the format as specified by this query.
116+ *
117+ * @param $rows
118+ * @return array
119+ */
120+ public function populate ($ rows )
121+ {
122+ $ result = [];
123+
124+ if ($ this ->indexBy === null ) {
125+ return array_values ($ rows ); // reset storage internal keys
126+ }
127+
128+ foreach ($ rows as $ row ) {
129+ if (is_string ($ this ->indexBy )) {
130+ $ key = $ row [$ this ->indexBy ];
131+ } else {
132+ $ key = call_user_func ($ this ->indexBy , $ row );
133+ }
134+ $ result [$ key ] = $ row ;
135+ }
136+
137+ return $ result ;
138+ }
139+ }
0 commit comments