-
Notifications
You must be signed in to change notification settings - Fork 58
/
Select.php
633 lines (567 loc) 路 15.8 KB
/
Select.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
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
<?php
namespace ClanCats\Hydrahon\Query\Sql;
/**
* SQL query object
**
* @package Hydrahon
* @copyright 2015 Mario D枚ring
*/
use ClanCats\Hydrahon\Query\Expression;
class Select extends SelectBase
{
/**
* fields to be selected
*
* @var array
*/
protected $fields = array();
/**
* make a distinct selection
*
* @var bool
*/
protected $distinct = false;
/**
* order by container
*
* @var array
*/
protected $orders = array();
/**
* group by container
*
* @var array
*/
protected $groups = array();
/**
* join container
*
* @var array
*/
protected $joins = array();
/**
* group the results by a given key
*
* @var false|string
*/
protected $groupResults = false;
/**
* Forward a value as key
*
* @var false|string
*/
protected $forwardKey = false;
/**
* Distinct select setter
*
* @param bool $ignore
* @return self
*/
public function distinct($distinct = true)
{
$this->distinct = $distinct; return $this;
}
/**
* Set the selected fields fields
*
* ->fields('title')
*
* ->fields(['id', 'name'])
*
* ->fields('id, name, created_at as created')
*
* @param array $values
* @return self
*/
public function fields($fields)
{
// we always have to reset the fields
$this->fields = array();
// when a string is given
if (is_string($fields))
{
$fields = $this->stringArgumentToArray($fields);
}
// it also could be an object
elseif (is_object($fields))
{
return $this->addField($fields);
}
// do nothing if we get nothing
if (empty($fields) || $fields === array('*') || $fields === array('')) { return $this; }
// add the fields
foreach($fields as $key => $field)
{
// when we have a string as key we have an alias definition
if (is_string($key))
{
$this->addField($key, $field);
} else {
$this->addField($field);
}
}
return $this;
}
/**
* Add a single select field
*
* ->addField('title')
*
* @param string $field
* @param string $alias
* @return self
*/
public function addField($field, $alias = null)
{
$this->fields[] = array($field, $alias); return $this;
}
/**
* Shortcut to add a count function
*
* ->addFieldCount('id')
*
* @param string $field
* @param string $alias
* @return self
*/
public function addFieldCount($field, $alias = null)
{
$this->addField(new Func('count', $field), $alias); return $this;
}
/**
* Shortcut to add a max function
*
* ->addFieldMax('views')
*
* @param string $field
* @param string $alias
* @return self
*/
public function addFieldMax($field, $alias = null)
{
$this->addField(new Func('max', $field), $alias); return $this;
}
/**
* Shortcut to add a min function
*
* ->addFieldMin('views')
*
* @param string $field
* @param string $alias
* @return self
*/
public function addFieldMin($field, $alias = null)
{
$this->addField(new Func('min', $field), $alias); return $this;
}
/**
* Shortcut to add a sum function
*
* ->addFieldSum('views')
*
* @param string $field
* @param string $alias
* @return self
*/
public function addFieldSum($field, $alias = null)
{
$this->addField(new Func('sum', $field), $alias); return $this;
}
/**
* Shortcut to add a avg function
*
* ->addFieldAvg('views')
*
* @param string $field
* @param string $alias
* @return self
*/
public function addFieldAvg($field, $alias = null)
{
$this->addField(new Func('avg', $field), $alias); return $this;
}
/**
* Shortcut to add a price function
*
* ->addFieldRound('price')
*
* @param string $field
* @param string $alias
* @return self
*/
public function addFieldRound($field, $decimals = 0, $alias = null)
{
$this->addField(new Func('round', $field, new Expression((int)$decimals)), $alias); return $this;
}
/**
* Add an order by statement to the current query
*
* ->orderBy('created_at')
* ->orderBy('modified_at', 'desc')
*
* // multiple order statements
* ->orderBy(['firstname', 'lastname'], 'desc')
*
* // muliple order statements with diffrent directions
* ->orderBy(['firstname' => 'asc', 'lastname' => 'desc'])
*
* @param array|string $cols
* @param string $order
* @return self
*/
public function orderBy($columns, $direction = 'asc')
{
if (is_string($columns))
{
$columns = $this->stringArgumentToArray($columns);
}
elseif ($columns instanceof Expression)
{
$this->orders[] = [$columns, $direction]; return $this;
}
foreach ($columns as $key => $column)
{
if (is_numeric($key))
{
$this->orders[$column] = $direction;
} else {
$this->orders[$key] = $column;
}
}
return $this;
}
/**
* Add a group by statement to the current query
*
* ->groupBy('id')
* ->gorupBy(['id', 'category'])
*
* @param array|string $keys
* @return self
*/
public function groupBy($groupKeys)
{
if (is_string($groupKeys))
{
$groupKeys = $this->stringArgumentToArray($groupKeys);
}
foreach ($groupKeys as $groupKey)
{
$this->groups[] = $groupKey;
}
return $this;
}
/**
* Add a join statement to the current query
*
* ->join('avatars', 'users.id', '=', 'avatars.user_id')
*
* @param array|string $table
* @param string $localKey
* @param string $operator
* @param string $referenceKey
* @param string $type
*
* @return self
*/
public function join($table, $localKey, $operator = null, $referenceKey = null, $type = 'left')
{
// validate the join type
if (!in_array($type, array('inner', 'left', 'right', 'outer')))
{
throw new Exception('Invalid join type "'.$type.'" given. Available type: inner, left, right, outer');
}
// to make nested joins possible you can pass an closure
// wich will create a new query where you can add your nested wheres
if (is_object($localKey) && ($localKey instanceof \Closure))
{
// create new query object
$subquery = new SelectJoin;
// run the closure callback on the sub query
call_user_func_array($localKey, array(&$subquery));
// add the join
$this->joins[] = array($type, $table, $subquery); return $this;
}
$this->joins[] = array($type, $table, $localKey, $operator, $referenceKey); return $this;
}
/**
* Left join same as join with special type
*
* @param array|string $table
* @param string $localKey
* @param string $operator
* @param string $referenceKey
*
* @return self
*/
public function leftJoin($table, $localKey, $operator = null, $referenceKey = null)
{
return $this->join($table, $localKey, $operator, $referenceKey, 'left');
}
/**
* Left join same as join with special type
*
* @param array|string $table
* @param string $localKey
* @param string $operator
* @param string $referenceKey
*
* @return self
*/
public function rightJoin($table, $localKey, $operator = null, $referenceKey = null)
{
return $this->join($table, $localKey, $operator, $referenceKey, 'right');
}
/**
* Left join same as join with special type
*
* @param array|string $table
* @param string $localKey
* @param string $operator
* @param string $referenceKey
*
* @return self
*/
public function innerJoin($table, $localKey, $operator = null, $referenceKey = null)
{
return $this->join($table, $localKey, $operator, $referenceKey, 'inner');
}
/**
* Left join same as join with special type
*
* @param array|string $table
* @param string $localKey
* @param string $operator
* @param string $referenceKey
*
* @return self
*/
public function outerJoin($table, $localKey, $operator = null, $referenceKey = null)
{
return $this->join($table, $localKey, $operator, $referenceKey, 'outer');
}
/**
* Forward a result value as array key
*
* @param string|bool $key
* @return self
*/
public function forwardKey($key = true)
{
if ($key === false) {
$this->forwardKey = false;
} elseif ($key === true) {
$this->forwardKey = \ClanCats::$config->get('database.default_primary_key', 'id');
} else {
$this->forwardKey = $key;
}
return $this;
}
/**
* Group results by a column
*
* example:
* array( 'name' => 'John', 'age' => 18, ),
* array( 'name' => 'Jeff', 'age' => 32, ),
* array( 'name' => 'Jenny', 'age' => 18, ),
* To:
* '18' => array(
* array( 'name' => 'John', 'age' => 18 ),
* array( 'name' => 'Jenny', 'age' => 18 ),
* ),
* '32' => array(
* array( 'name' => 'Jeff', 'age' => 32 ),
* ),
*
* @param string|bool $key
* @return self
*/
public function groupResults($key)
{
if ($key === false) {
$this->groupResults = false;
} else {
$this->groupResults = $key;
}
return $this;
}
/**
* Executes the 'executeResultFetcher' callback and handles the results
*/
public function get()
{
// run the callbacks to retirve the results
$results = $this->executeResultFetcher();
// we always exprect an array here!
if (!is_array($results) || empty($results))
{
$results = array();
}
// In case we should forward a key means using a value
// from every result as array key.
if ((!empty($results)) && $this->forwardKey !== false && is_string($this->forwardKey))
{
$rawResults = $results;
$results = array();
// check if the collection is beeing fetched
// as an associated array
if (!is_array(reset($rawResults)))
{
throw new Exception('Cannot forward key, the result is no associated array.');
}
foreach ($rawResults as $result)
{
$results[$result[$this->forwardKey]] = $result;
}
}
// Group the resuls by a items value
if ((!empty($results)) && $this->groupResults !== false && is_string($this->groupResults))
{
$rawResults = $results;
$results = array();
// check if the collection is beeing fetched
// as an associated array
if (!is_array(reset($rawResults)))
{
throw new Exception('Cannot forward key, the result is no associated array.');
}
foreach ($rawResults as $key => $result)
{
$results[$result[$this->groupResults]][$key] = $result;
}
}
// when the limit is specified to exactly one result we
// return directly that one result instead of the entire array
if ($this->limit === 1)
{
$results = reset($results);
}
return $results;
}
/**
* Executes the 'executeResultFetcher' callback and handles the results
*
* @param string $handler
* @return mixed
*/
public function run()
{
// run is basically ported from CCF, laravels `get` just feels
// much better so lets move on...
trigger_error('The `run` method is deprecated, `get` method instead.', E_USER_DEPRECATED);
// run the get method
return $this->get();
}
/**
* Get one result sets limit to 1 and executes
*
* @return mixed
*/
public function one()
{
return $this->limit(0, 1)->get();
}
/**
* Find something, means select one record by key
*
* @param int $id
* @param string $key
* @return mixed
*/
public function find($id, $key = 'id')
{
return $this->where($key, $id)->one();
}
/**
* Get the first result by key
*
* @param string $key
* @return mixed
*/
public function first($key = 'id')
{
return $this->orderBy($key, 'asc')->one();
}
/**
* Get the last result by key
*
* @param string $key
* @param string $name
* @return mixed
*/
public function last($key = 'id')
{
return $this->orderBy($key, 'desc')->one();
}
/**
* Just get a single value from the db
*
* @param string $column
* @return mixed
*/
public function column($column)
{
$result = $this->fields($column)->one();
// only return something if something is found
if (is_array($result))
{
return reset($result);
}
}
/**
* Just return the number of results
*
* @param string $field
* @return int
*/
public function count($field = null)
{
// when no field is given we use *
if (is_null($field))
{
$field = new Expression('*');
}
// return the column
return (int) $this->column(new Func('count', $field));
}
/**
* Helper the get the sum of a column
*
* @param string $field
* @return int
*/
public function sum($field)
{
return $this->column(new Func('sum', $field));
}
/**
* Helper the get the max of a column
*
* @param string $field
* @return int
*/
public function max($field)
{
return $this->column(new Func('max', $field));
}
/**
* Helper the get the min of a column
*
* @param string $field
* @return int
*/
public function min($field)
{
return $this->column(new Func('min', $field));
}
/**
* Helper the get the avarage of a column
*
* @param string $field
* @return int
*/
public function avg($field)
{
return $this->column(new Func('avg', $field));
}
}