forked from rjjakes/wordpress-orm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryBuilder.php
More file actions
266 lines (216 loc) · 6.3 KB
/
QueryBuilder.php
File metadata and controls
266 lines (216 loc) · 6.3 KB
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
<?php
namespace Symlink\ORM;
use Symlink\ORM\Repositories\BaseRepository;
class QueryBuilder {
private $where;
private $order_by;
private $limit;
/**
* The prepared query run through $wpdb->prepare().
* @var
*/
private $query;
/**
* Reference to the repository.
* @var \Symlink\ORM\Repositories\BaseRepository
*/
private $repository;
/**
* QueryBuilder constructor.
*/
public function __construct( BaseRepository $repository ) {
// Set some default values.
$this->where = [];
$this->order_by;
$this->limit;
// And store the sent repository.
$this->repository = $repository;
}
/**
* Add a WHERE clause to the query.
*
* @param $property
* @param $value
* @param $operator
*
* @return $this
* @throws \Symlink\ORM\Exceptions\InvalidOperatorException
* @throws \Symlink\ORM\Exceptions\PropertyDoesNotExistException
*/
public function where( $property, $value, $operator ) {
// Check the property exists.
if ( ! in_array( $property, $this->repository->getObjectProperties() ) && $property != 'ID' ) {
throw new \Symlink\ORM\Exceptions\PropertyDoesNotExistException( sprintf( __( 'Property %s does not exist in model %s.' ), $property, $this->repository->getObjectClass() ) );
}
// Check the operator is valid.
if ( ! in_array( $operator, [
'<',
'<=',
'=',
'!=',
'<>',
'>',
'>=',
'IN',
'NOT IN',
'LIKE',
'NOT LIKE',
'REGEXP',
'NOT REGEXP',
] )
) {
throw new \Symlink\ORM\Exceptions\InvalidOperatorException( sprintf( __( 'Operator %s is not valid.' ), $operator ) );
}
// Add the entry.
$this->where[] = [
'property' => $property,
'operator' => $operator,
'value' => $value,
'placeholder' => $this->repository->getObjectPropertyPlaceholders()[ $property ]
];
return $this;
}
/**
* Set the ORDER BY clause.
*
* @param $property
* @param $operator
*
* @return $this
* @throws \Symlink\ORM\Exceptions\InvalidOperatorException
* @throws \Symlink\ORM\Exceptions\PropertyDoesNotExistException
*/
public function orderBy( $property, $operator ) {
// Check the property exists.
if ( ! in_array( $property, $this->repository->getObjectProperties() ) && $property != 'ID' ) {
throw new \Symlink\ORM\Exceptions\PropertyDoesNotExistException( sprintf( __( 'Property %s does not exist in model %s.' ), $property, $this->repository->getObjectClass() ) );
}
// Check the operator is valid.
if ( ! in_array( $operator, [
'ASC',
'DESC',
] )
) {
throw new \Symlink\ORM\Exceptions\InvalidOperatorException( sprintf( __( 'Operator %s is not valid.' ), $operator ) );
}
// Save it
$this->order_by = "ORDER BY " . $property . " " . $operator . "
";
return $this;
}
/**
* Set the limit clause.
*
* @param $count
* @param int $offset
*
* @return $this
*/
public function limit( $count, $offset = 0 ) {
// Ignore if not valid.
if ( is_numeric( $offset ) && is_numeric( $count ) && $offset >= 0 && $count > 0 ) {
$this->limit = "LIMIT " . $count . " OFFSET " . $offset . "
";
}
return $this;
}
/**
* Build the query and process through $wpdb->prepare().
* @return $this
*/
public function buildQuery() {
global $wpdb;
$values = [];
$sql = "SELECT * FROM " . $wpdb->prefix . $this->repository->getDBTable() . "
";
// Combine the WHERE clauses and add to the SQL statement.
if ( count( $this->where ) ) {
$sql .= "WHERE
";
$combined_where = [];
foreach ( $this->where as $where ) {
// Operators is not "IN" or "NOT IN"
if ( $where['operator'] != 'IN' && $where['operator'] != 'NOT IN' ) {
$combined_where[] = $where['property'] . " " . $where['operator'] . " " . $where['placeholder'] . "
";
$values[] = $where['value'];
} // Operator is "IN" or "NOT IN"
else {
// Fail silently.
if ( is_array( $where['value'] ) ) {
$combined_where[] = $where['property'] . " " . $where['operator'] . " (" . implode( ", ", array_pad( [], count( $where['value'] ), $where['placeholder'] ) ) . ")
";
$values = array_merge( $values, $where['value'] );
}
}
}
$sql .= implode( ' AND ', $combined_where ); // @todo - should allow more than AND in future.
}
// Add the ORDER BY clause.
if ( $this->order_by ) {
$sql .= $this->order_by;
}
// Add the LIMIT clause.
if ( $this->limit ) {
$sql .= $this->limit;
}
// Save it.
$this->query = count( $this->where ) ? $wpdb->prepare( $sql, $values ) : $sql;
return $this;
}
/**
* Run the query returning either a single object or an array of objects.
*
* @param bool $always_array
*
* @return array|mixed
* @throws \Symlink\ORM\Exceptions\NoQueryException
*/
public function getResults( $always_array = false ) {
global $wpdb;
if ( $this->query ) {
// Classname for this repository.
$object_classname = $this->repository->getObjectClass();
/**
* Get in cache if exists or retrieve in DB and save in cache for later use in the current request
*/
// Cache group (Where the cache contents are grouped)
$cache_group = 'wordpress_orm_getResults';
// Cache key
$cache_key = md5( $this->query );
$results = wp_cache_get( $cache_key, $cache_group );
if ( $results === false ) {
// Get items
$results = $wpdb->get_results( $this->query );
// Cache result
wp_cache_add( $cache_key, $results, $cache_group );
}
// Loop through the database results, building the objects.
$objects = array_map( function ( $result ) use ( &$object_classname ) {
// Create a new blank object.
$object = new $object_classname();
// Fill in all the properties.
array_walk( $result, function ( $value, $property ) use ( &$object ) {
$object->set( $property, $value );
} );
// Track the object.
$em = Manager::getManager();
$em->track( $object );
// Save it.
return $object;
}, $results );
// There were no results.
if ( ! count( $objects ) ) {
return null;
}
// Return just an object if there was only one result.
if ( count( $objects ) == 1 && ! $always_array ) {
return $objects[0];
}
// Otherwise, the return an array of objects.
return $objects;
} else {
throw new \Symlink\ORM\Exceptions\NoQueryException( __( 'No query was built. Run ->buildQuery() first.' ) );
}
}
}