forked from flourishlib/flourish-classes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fRecordSet.php
1990 lines (1693 loc) · 72.1 KB
/
fRecordSet.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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* A lightweight, iterable set of fActiveRecord-based objects
*
* @copyright Copyright (c) 2007-2011 Will Bond
* @author Will Bond [wb] <[email protected]>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fRecordSet
*
* @version 1.0.0b45
* @changes 1.0.0b45 Added support for the starts with like, `^~`, and ends with like, `$~`, operators to both ::build() and ::filter() [wb, 2011-06-20]
* @changes 1.0.0b44 Backwards Compatibility Break - ::sort() and ::sortByCallback() now return a new fRecordSet instead of sorting the record set in place [wb, 2011-06-20]
* @changes 1.0.0b43 Added the ability to pass SQL and values to ::buildFromSQL(), added the ability to manually pass the `$limit` and `$page` to ::buildFromArray() and ::buildFromSQL(), changed ::slice() to remember `$limit` and `$page` if possible when `$remember_original_count` is `TRUE` [wb, 2011-01-11]
* @changes 1.0.0b42 Updated class to use fORM::getRelatedClass() [wb, 2010-11-24]
* @changes 1.0.0b41 Added support for PHP 5.3 namespaced fActiveRecord classes [wb, 2010-11-11]
* @changes 1.0.0b40 Added the ::tally() method [wb, 2010-09-28]
* @changes 1.0.0b39 Backwards Compatibility Break - removed the methods ::fetchRecord(), ::current(), ::key(), ::next(), ::rewind() and ::valid() and the Iterator interface - and the `$pointer` parameter for callbacks registered via fORM::registerRecordSetMethod() was replaced with the `$method_name` parameter - added the methods ::getIterator(), ::getLimit(), ::getPage(), ::getPages(), ::getRecord(), ::offsetExists(), ::offsetGet(), ::offsetSet() and ::offsetUnset() and the IteratorAggregate and ArrayAccess interfaces [wb, 2010-09-28]
* @changes 1.0.0b38 Updated code to work with the new fORM API [wb, 2010-08-06]
* @changes 1.0.0b37 Fixed a typo/bug in ::reduce() [wb, 2010-06-30]
* @changes 1.0.0b36 Replaced create_function() with a private method call [wb, 2010-06-08]
* @changes 1.0.0b35 Added the ::chunk() and ::split() methods [wb, 2010-05-20]
* @changes 1.0.0b34 Added an integer cast to ::count() to fix issues with the dblib MSSQL driver [wb, 2010-04-09]
* @changes 1.0.0b33 Updated the class to force configure classes before peforming actions with them [wb, 2010-03-30]
* @changes 1.0.0b32 Fixed a column aliasing issue with SQLite [wb, 2010-01-25]
* @changes 1.0.0b31 Added the ability to compare columns in ::build() with the `=:`, `!:`, `<:`, `<=:`, `>:` and `>=:` operators [wb, 2009-12-08]
* @changes 1.0.0b30 Fixed a bug affecting where conditions with columns that are not null but have a default value [wb, 2009-11-03]
* @changes 1.0.0b29 Updated code for the new fORMDatabase and fORMSchema APIs [wb, 2009-10-28]
* @changes 1.0.0b28 Fixed ::prebuild() and ::precount() to work across all databases, changed SQL statements to use value placeholders, identifier escaping and schema support [wb, 2009-10-22]
* @changes 1.0.0b27 Changed fRecordSet::build() to fix bad $page numbers instead of throwing an fProgrammerException [wb, 2009-10-05]
* @changes 1.0.0b26 Updated the documentation for ::build() and ::filter() to reflect new functionality [wb, 2009-09-21]
* @changes 1.0.0b25 Fixed ::map() to work with string-style static method callbacks in PHP 5.1 [wb, 2009-09-18]
* @changes 1.0.0b24 Backwards Compatibility Break - renamed ::buildFromRecords() to ::buildFromArray(). Added ::buildFromCall(), ::buildFromMap() and `::build{RelatedRecords}()` [wb, 2009-09-16]
* @changes 1.0.0b23 Added an extra parameter to ::diff(), ::filter(), ::intersect(), ::slice() and ::unique() to save the number of records in the current set as the non-limited count for the new set [wb, 2009-09-15]
* @changes 1.0.0b22 Changed ::__construct() to accept any Iterator instead of just an fResult object [wb, 2009-08-12]
* @changes 1.0.0b21 Added performance tweaks to ::prebuild() and ::precreate() [wb, 2009-07-31]
* @changes 1.0.0b20 Changed the class to implement Countable, making the [http://php.net/count `count()`] function work [wb, 2009-07-29]
* @changes 1.0.0b19 Fixed bugs with ::diff() and ::intersect() and empty record sets [wb, 2009-07-29]
* @changes 1.0.0b18 Added method chaining support to prebuild, precount and precreate methods [wb, 2009-07-15]
* @changes 1.0.0b17 Changed ::__call() to pass the parameters to the callback [wb, 2009-07-14]
* @changes 1.0.0b16 Updated documentation for the intersection operator `><` [wb, 2009-07-13]
* @changes 1.0.0b15 Added the methods ::diff() and ::intersect() [wb, 2009-07-13]
* @changes 1.0.0b14 Added the methods ::contains() and ::unique() [wb, 2009-07-09]
* @changes 1.0.0b13 Added documentation to ::build() about the intersection operator `><` [wb, 2009-07-09]
* @changes 1.0.0b12 Added documentation to ::build() about the `AND LIKE` operator `&~` [wb, 2009-07-09]
* @changes 1.0.0b11 Added documentation to ::build() about the `NOT LIKE` operator `!~` [wb, 2009-07-08]
* @changes 1.0.0b10 Moved the private method ::checkConditions() to fActiveRecord::checkConditions() [wb, 2009-07-08]
* @changes 1.0.0b9 Changed ::build() to only fall back to ordering by primary keys if one exists [wb, 2009-06-26]
* @changes 1.0.0b8 Updated ::merge() to accept arrays of fActiveRecords or a single fActiveRecord in addition to an fRecordSet [wb, 2009-06-02]
* @changes 1.0.0b7 Backwards Compatibility Break - Removed ::flagAssociate() and ::isFlaggedForAssociation(), callbacks registered via fORM::registerRecordSetMethod() no longer receive the `$associate` parameter [wb, 2009-06-02]
* @changes 1.0.0b6 Changed ::tossIfEmpty() to return the record set to allow for method chaining [wb, 2009-05-18]
* @changes 1.0.0b5 ::build() now allows NULL for `$where_conditions` and `$order_bys`, added a check to the SQL passed to ::buildFromSQL() [wb, 2009-05-03]
* @changes 1.0.0b4 ::__call() was changed to prevent exceptions coming from fGrammar when an unknown method is called [wb, 2009-03-27]
* @changes 1.0.0b3 ::sort() and ::sortByCallback() now return the record set to allow for method chaining [wb, 2009-03-23]
* @changes 1.0.0b2 Added support for != and <> to ::build() and ::filter() [wb, 2008-12-04]
* @changes 1.0.0b The initial implementation [wb, 2007-08-04]
*/
class fRecordSet implements IteratorAggregate, ArrayAccess, Countable
{
// The following constants allow for nice looking callbacks to static methods
const build = 'fRecordSet::build';
const buildFromArray = 'fRecordSet::buildFromArray';
const buildFromSQL = 'fRecordSet::buildFromSQL';
/**
* Creates an fRecordSet by specifying the class to create plus the where conditions and order by rules
*
* The where conditions array can contain `key => value` entries in any of
* the following formats:
*
* {{{
* 'column=' => VALUE, // column = VALUE
* 'column!' => VALUE // column <> VALUE
* 'column!=' => VALUE // column <> VALUE
* 'column<>' => VALUE // column <> VALUE
* 'column~' => VALUE // column LIKE '%VALUE%'
* 'column^~' => VALUE // column LIKE 'VALUE%'
* 'column$~' => VALUE // column LIKE '%VALUE'
* 'column!~' => VALUE // column NOT LIKE '%VALUE%'
* 'column<' => VALUE // column < VALUE
* 'column<=' => VALUE // column <= VALUE
* 'column>' => VALUE // column > VALUE
* 'column>=' => VALUE // column >= VALUE
* 'column=:' => 'other_column' // column = other_column
* 'column!:' => 'other_column' // column <> other_column
* 'column!=:' => 'other_column' // column <> other_column
* 'column<>:' => 'other_column' // column <> other_column
* 'column<:' => 'other_column' // column < other_column
* 'column<=:' => 'other_column' // column <= other_column
* 'column>:' => 'other_column' // column > other_column
* 'column>=:' => 'other_column' // column >= other_column
* 'column=' => array(VALUE, VALUE2, ... ) // column IN (VALUE, VALUE2, ... )
* 'column!' => array(VALUE, VALUE2, ... ) // column NOT IN (VALUE, VALUE2, ... )
* 'column!=' => array(VALUE, VALUE2, ... ) // column NOT IN (VALUE, VALUE2, ... )
* 'column<>' => array(VALUE, VALUE2, ... ) // column NOT IN (VALUE, VALUE2, ... )
* 'column~' => array(VALUE, VALUE2, ... ) // (column LIKE '%VALUE%' OR column LIKE '%VALUE2%' OR column ... )
* 'column^~' => array(VALUE, VALUE2, ... ) // (column LIKE 'VALUE%' OR column LIKE 'VALUE2%' OR column ... )
* 'column$~' => array(VALUE, VALUE2, ... ) // (column LIKE '%VALUE' OR column LIKE '%VALUE2' OR column ... )
* 'column&~' => array(VALUE, VALUE2, ... ) // (column LIKE '%VALUE%' AND column LIKE '%VALUE2%' AND column ... )
* 'column!~' => array(VALUE, VALUE2, ... ) // (column NOT LIKE '%VALUE%' AND column NOT LIKE '%VALUE2%' AND column ... )
* 'column!|column2<|column3=' => array(VALUE, VALUE2, VALUE3) // (column <> '%VALUE%' OR column2 < '%VALUE2%' OR column3 = '%VALUE3%')
* 'column|column2><' => array(VALUE, VALUE2) // WHEN VALUE === NULL: ((column2 IS NULL AND column = VALUE) OR (column2 IS NOT NULL AND column <= VALUE AND column2 >= VALUE))
* // WHEN VALUE !== NULL: ((column <= VALUE AND column2 >= VALUE) OR (column >= VALUE AND column <= VALUE2))
* 'column|column2|column3~' => VALUE // (column LIKE '%VALUE%' OR column2 LIKE '%VALUE%' OR column3 LIKE '%VALUE%')
* 'column|column2|column3~' => array(VALUE, VALUE2, ... ) // ((column LIKE '%VALUE%' OR column2 LIKE '%VALUE%' OR column3 LIKE '%VALUE%') AND (column LIKE '%VALUE2%' OR column2 LIKE '%VALUE2%' OR column3 LIKE '%VALUE2%') AND ... )
* }}}
*
* When creating a condition in the form `column|column2|column3~`, if the
* value for the condition is a single string that contains spaces, the
* string will be parsed for search terms. The search term parsing will
* handle quoted phrases and normal words and will strip punctuation and
* stop words (such as "the" and "a").
*
* The order bys array can contain `key => value` entries in any of the
* following formats:
*
* {{{
* 'column' => 'asc' // 'first_name' => 'asc'
* 'column' => 'desc' // 'last_name' => 'desc'
* 'expression' => 'asc' // "CASE first_name WHEN 'smith' THEN 1 ELSE 2 END" => 'asc'
* 'expression' => 'desc' // "CASE first_name WHEN 'smith' THEN 1 ELSE 2 END" => 'desc'
* }}}
*
* The column in both the where conditions and order bys can be in any of
* the formats:
*
* {{{
* 'column' // e.g. 'first_name'
* 'current_table.column' // e.g. 'users.first_name'
* 'related_table.column' // e.g. 'user_groups.name'
* 'related_table{route}.column' // e.g. 'user_groups{user_group_id}.name'
* 'related_table=>once_removed_related_table.column' // e.g. 'user_groups=>permissions.level'
* 'related_table{route}=>once_removed_related_table.column' // e.g. 'user_groups{user_group_id}=>permissions.level'
* 'related_table=>once_removed_related_table{route}.column' // e.g. 'user_groups=>permissions{read}.level'
* 'related_table{route}=>once_removed_related_table{route}.column' // e.g. 'user_groups{user_group_id}=>permissions{read}.level'
* 'column||other_column' // e.g. 'first_name||last_name' - this concatenates the column values
* }}}
*
* In addition to using plain column names for where conditions, it is also
* possible to pass an aggregate function wrapped around a column in place
* of a column name, but only for certain comparison types. //Note that for
* column comparisons, the function may be placed on either column or both.//
*
* {{{
* 'function(column)=' => VALUE, // function(column) = VALUE
* 'function(column)!' => VALUE // function(column) <> VALUE
* 'function(column)!= => VALUE // function(column) <> VALUE
* 'function(column)<>' => VALUE // function(column) <> VALUE
* 'function(column)~' => VALUE // function(column) LIKE '%VALUE%'
* 'function(column)^~' => VALUE // function(column) LIKE 'VALUE%'
* 'function(column)$~' => VALUE // function(column) LIKE '%VALUE'
* 'function(column)!~' => VALUE // function(column) NOT LIKE '%VALUE%'
* 'function(column)<' => VALUE // function(column) < VALUE
* 'function(column)<=' => VALUE // function(column) <= VALUE
* 'function(column)>' => VALUE // function(column) > VALUE
* 'function(column)>=' => VALUE // function(column) >= VALUE
* 'function(column)=:' => 'other_column' // function(column) = other_column
* 'function(column)!:' => 'other_column' // function(column) <> other_column
* 'function(column)!=:' => 'other_column' // function(column) <> other_column
* 'function(column)<>:' => 'other_column' // function(column) <> other_column
* 'function(column)<:' => 'other_column' // function(column) < other_column
* 'function(column)<=:' => 'other_column' // function(column) <= other_column
* 'function(column)>:' => 'other_column' // function(column) > other_column
* 'function(column)>=:' => 'other_column' // function(column) >= other_column
* 'function(column)=' => array(VALUE, VALUE2, ... ) // function(column) IN (VALUE, VALUE2, ... )
* 'function(column)!' => array(VALUE, VALUE2, ... ) // function(column) NOT IN (VALUE, VALUE2, ... )
* 'function(column)!=' => array(VALUE, VALUE2, ... ) // function(column) NOT IN (VALUE, VALUE2, ... )
* 'function(column)<>' => array(VALUE, VALUE2, ... ) // function(column) NOT IN (VALUE, VALUE2, ... )
* }}}
*
* The aggregate functions `AVG()`, `COUNT()`, `MAX()`, `MIN()` and
* `SUM()` are supported across all database types.
*
* Below is an example of using where conditions and order bys. Please note
* that values should **not** be escaped for the database, but should just
* be normal PHP values.
*
* {{{
* #!php
* return fRecordSet::build(
* 'User',
* array(
* 'first_name=' => 'John',
* 'status!' => 'Inactive',
* 'groups.group_id=' => 2
* ),
* array(
* 'last_name' => 'asc',
* 'date_joined' => 'desc'
* )
* );
* }}}
*
* @param string $class The class to create the fRecordSet of
* @param array $where_conditions The `column => value` comparisons for the `WHERE` clause
* @param array $order_bys The `column => direction` values to use for the `ORDER BY` clause
* @param integer $limit The number of records to fetch
* @param integer $page The page offset to use when limiting records
* @return fRecordSet A set of fActiveRecord objects
*/
static public function build($class, $where_conditions=array(), $order_bys=array(), $limit=NULL, $page=NULL)
{
fActiveRecord::validateClass($class);
fActiveRecord::forceConfigure($class);
$db = fORMDatabase::retrieve($class, 'read');
$schema = fORMSchema::retrieve($class);
$table = fORM::tablize($class);
$params = array($db->escape("SELECT %r.* FROM :from_clause", $table));
if ($where_conditions) {
$having_conditions = fORMDatabase::splitHavingConditions($where_conditions);
} else {
$having_conditions = NULL;
}
if ($where_conditions) {
$params[0] .= ' WHERE ';
$params = fORMDatabase::addWhereClause($db, $schema, $params, $table, $where_conditions);
}
$params[0] .= ' :group_by_clause ';
if ($having_conditions) {
$params[0] .= ' HAVING ';
$params = fORMDatabase::addHavingClause($db, $schema, $params, $table, $having_conditions);
}
// If no ordering is specified, order by the primary key
if (!$order_bys) {
$order_bys = array();
foreach ($schema->getKeys($table, 'primary') as $pk_column) {
$order_bys[$table . '.' . $pk_column] = 'ASC';
}
}
$params[0] .= ' ORDER BY ';
$params = fORMDatabase::addOrderByClause($db, $schema, $params, $table, $order_bys);
$params = fORMDatabase::injectFromAndGroupByClauses($db, $schema, $params, $table);
// Add the limit clause and create a query to get the non-limited total
$non_limited_count_sql = NULL;
if ($limit !== NULL) {
$pk_columns = array();
foreach ($schema->getKeys($table, 'primary') as $pk_column) {
$pk_columns[] = $table . '.' . $pk_column;
}
$non_limited_count_sql = str_replace(
$db->escape('SELECT %r.*', $table),
$db->escape('SELECT %r', $pk_columns),
$params[0]
);
$non_limited_count_sql = preg_replace('#\s+ORDER BY.*$#', '', $non_limited_count_sql);
$non_limited_count_sql = $db->escape('SELECT count(*) FROM (' . $non_limited_count_sql . ') subquery', array_slice($params, 1));
$params[0] .= ' LIMIT ' . $limit;
if ($page !== NULL) {
if (!is_numeric($page) || $page < 1) {
$page = 1;
}
$params[0] .= ' OFFSET ' . (($page-1) * $limit);
}
} else {
$page = 1;
}
return new fRecordSet($class, call_user_func_array($db->translatedQuery, $params), $non_limited_count_sql, $limit, $page);
}
/**
* Creates an fRecordSet from an array of records
*
* @internal
*
* @param string|array $class The class or classes of the records
* @param array $records The records to create the set from, the order of the record set will be the same as the order of the array.
* @param integer $total_records The total number of records - this should only be provided if the array is a segment of a larger array - this is informational only and does not affect the array
* @param integer $limit The maximum number of records the array was limited to - this is informational only and does not affect the array
* @param integer $page The page of records the array is from - this is informational only and does not affect the array
* @return fRecordSet A set of fActiveRecord objects
*/
static public function buildFromArray($class, $records, $total_records=NULL, $limit=NULL, $page=1)
{
if (is_array($class)) {
foreach ($class as $_class) {
fActiveRecord::validateClass($_class);
fActiveRecord::forceConfigure($_class);
}
} else {
fActiveRecord::validateClass($class);
fActiveRecord::forceConfigure($class);
}
if (!is_array($records)) {
throw new fProgrammerException('The records specified are not in an array');
}
return new fRecordSet($class, $records, $total_records, $limit, $page);
}
/**
* Creates an fRecordSet from an SQL statement
*
* The SQL statement should select all columns from a single table with a *
* pattern since that is what an fActiveRecord models. If any columns are
* left out or added, strange error may happen when loading or saving
* records.
*
* Here is an example of an appropriate SQL statement:
*
* {{{
* #!sql
* SELECT users.* FROM users INNER JOIN groups ON users.group_id = groups.group_id WHERE groups.name = 'Public'
* }}}
*
* Here is an example of a SQL statement that will cause errors:
*
* {{{
* #!sql
* SELECT users.*, groups.name FROM users INNER JOIN groups ON users.group_id = groups.group_id WHERE groups.group_id = 2
* }}}
*
* The `$non_limited_count_sql` should only be passed when the `$sql`
* contains a `LIMIT` clause and should contain a count of the records when
* a `LIMIT` is not imposed.
*
* Here is an example of a `$sql` statement with a `LIMIT` clause and a
* corresponding `$non_limited_count_sql`:
*
* {{{
* #!php
* fRecordSet::buildFromSQL('User', 'SELECT * FROM users LIMIT 5', 'SELECT count(*) FROM users');
* }}}
*
* The `$non_limited_count_sql` is used when ::count() is called with `TRUE`
* passed as the parameter.
*
* Both the `$sql` and `$non_limited_count_sql` can be passed as a string
* SQL statement, or an array containing a SQL statement and the values to
* escape into it:
*
* {{{
* #!php
* fRecordSet::buildFromSQL(
* 'User',
* array("SELECT * FROM users WHERE date_created > %d LIMIT %i OFFSET %i", $start_date, 10, 10*($page-1)),
* array("SELECT * FROM users WHERE date_created > %d", $start_date),
* 10,
* $page
* )
* }}}
*
* @param string $class The class to create the fRecordSet of
* @param string|array $sql The SQL to create the set from, or an array of the SQL statement plus values to escape
* @param string|array $non_limited_count_sql An SQL statement, or an array of the SQL statement plus values to escape, to get the total number of rows that would have been returned if a `LIMIT` clause had not been used. Should only be passed if a `LIMIT` clause is used in `$sql`.
* @param integer $limit The number of records the SQL statement was limited to - this is information only and does not affect the SQL
* @param integer $page The page of records the SQL statement returned - this is information only and does not affect the SQL
* @return fRecordSet A set of fActiveRecord objects
*/
static public function buildFromSQL($class, $sql, $non_limited_count_sql=NULL, $limit=NULL, $page=1)
{
fActiveRecord::validateClass($class);
fActiveRecord::forceConfigure($class);
if (!preg_match('#^\s*SELECT\s*(DISTINCT|ALL)?\s*(("?\w+"?\.)?"?\w+"?\.)?\*\s*FROM#i', is_array($sql) ? $sql[0] : $sql)) {
throw new fProgrammerException(
'The SQL statement specified, %s, does not appear to be in the form SELECT * FROM table',
$sql
);
}
$db = fORMDatabase::retrieve($class, 'read');
if (is_array($sql)) {
$result = call_user_func_array($db->translatedQuery, $sql);;
} else {
$result = $db->translatedQuery($sql);
}
if (is_array($non_limited_count_sql)) {
$non_limited_count_sql = call_user_func_array($db->escape, $non_limited_count_sql);
}
return new fRecordSet(
$class,
$result,
$non_limited_count_sql,
$limit,
$page
);
}
/**
* Composes text using fText if loaded
*
* @param string $message The message to compose
* @param mixed $component A string or number to insert into the message
* @param mixed ...
* @return string The composed and possible translated message
*/
static protected function compose($message)
{
$args = array_slice(func_get_args(), 1);
if (class_exists('fText', FALSE)) {
return call_user_func_array(
array('fText', 'compose'),
array($message, $args)
);
} else {
return vsprintf($message, $args);
}
}
/**
* Counts the number of records that match the conditions specified
*
* @param string $class The class of records to count
* @param mixed $where_conditions An array of where clause parameters in the same format as ::build()
* @return integer The number of records
*/
static public function tally($class, $where_conditions=array())
{
fActiveRecord::validateClass($class);
fActiveRecord::forceConfigure($class);
$db = fORMDatabase::retrieve($class, 'read');
$schema = fORMSchema::retrieve($class);
$table = fORM::tablize($class);
$pk_columns = array();
foreach ($schema->getKeys($table, 'primary') as $pk_column) {
$pk_columns[] = $table . '.' . $pk_column;
}
$params = array($db->escape("SELECT COUNT(*) FROM (SELECT %r FROM :from_clause", $pk_columns));
if ($where_conditions) {
$having_conditions = fORMDatabase::splitHavingConditions($where_conditions);
} else {
$having_conditions = NULL;
}
if ($where_conditions) {
$params[0] .= ' WHERE ';
$params = fORMDatabase::addWhereClause($db, $schema, $params, $table, $where_conditions);
}
$params[0] .= ' :group_by_clause ';
if ($having_conditions) {
$params[0] .= ' HAVING ';
$params = fORMDatabase::addHavingClause($db, $schema, $params, $table, $having_conditions);
}
$params[0] .= ') subquery';
$params = fORMDatabase::injectFromAndGroupByClauses($db, $schema, $params, $table);
return call_user_func_array($db->translatedQuery, $params)->fetchScalar();
}
/**
* The class of the contained records
*
* @var string|array
*/
private $class = NULL;
/**
* The limit that was used when creating the set
*
* @var integer
*/
private $limit = NULL;
/**
* The page of results the record set represents
*
* @var integer
*/
private $page = 1;
/**
* The number of rows that would have been returned if a `LIMIT` clause had not been used, or the SQL to get that number
*
* @var integer|string
*/
private $non_limited_count = NULL;
/**
* An array of the records in the set, initially empty
*
* @var array
*/
private $records = array();
/**
* Allows for preloading various data related to the record set in single database queries, as opposed to one query per record
*
* This method will handle methods in the format `verbRelatedRecords()` for
* the verbs `build`, `prebuild`, `precount` and `precreate`.
*
* `build` calls `create{RelatedClass}()` on each record in the set and
* returns the result as a new record set. The relationship route can be
* passed as an optional parameter.
*
* `prebuild` builds *-to-many record sets for all records in the record
* set. `precount` will count records in *-to-many record sets for every
* record in the record set. `precreate` will create a *-to-one record
* for every record in the record set.
*
* @param string $method_name The name of the method called
* @param string $parameters The parameters passed
* @return void
*/
public function __call($method_name, $parameters)
{
if ($callback = fORM::getRecordSetMethod($method_name)) {
return call_user_func_array(
$callback,
array(
$this,
$this->class,
&$this->records,
$method_name,
$parameters
)
);
}
list($action, $subject) = fORM::parseMethod($method_name);
$route = ($parameters) ? $parameters[0] : NULL;
// This check prevents fGrammar exceptions being thrown when an unknown method is called
if (in_array($action, array('build', 'prebuild', 'precount', 'precreate'))) {
$related_class = fGrammar::singularize($subject);
$related_class_sans_namespace = $related_class;
if (!is_array($this->class)) {
$related_class = fORM::getRelatedClass($this->class, $related_class);
}
}
switch ($action) {
case 'build':
if ($route) {
$this->precreate($related_class, $route);
return $this->buildFromCall('create' . $related_class_sans_namespace, $route);
}
$this->precreate($related_class);
return $this->buildFromCall('create' . $related_class_sans_namespace);
case 'prebuild':
return $this->prebuild($related_class, $route);
case 'precount':
return $this->precount($related_class, $route);
case 'precreate':
return $this->precreate($related_class, $route);
}
throw new fProgrammerException(
'Unknown method, %s(), called',
$method_name
);
}
/**
* Sets the contents of the set
*
* @param string|array $class The type(s) of records the object will contain
* @param Iterator|array $records The Iterator object of the records to create or an array of records
* @param string|integer $non_limited_count An SQL statement to get the total number of records sans a `LIMIT` clause or a integer of the total number of records
* @param integer $limit The number of records the set was limited to
* @param integer $page The page of records that was built
* @return fRecordSet
*/
protected function __construct($class, $records=NULL, $non_limited_count=NULL, $limit=NULL, $page=1)
{
$this->class = (is_array($class) && count($class) == 1) ? current($class) : $class;
if ($non_limited_count !== NULL) {
$this->non_limited_count = $non_limited_count;
}
if ($records && is_object($records) && $records instanceof Iterator) {
while ($records->valid()) {
$this->records[] = new $class($records);
$records->next();
}
}
if (is_array($records)) {
$this->records = $records;
}
$this->limit = $limit;
$this->page = $page;
}
/**
* All requests that hit this method should be requests for callbacks
*
* @internal
*
* @param string $method The method to create a callback for
* @return callback The callback for the method requested
*/
public function __get($method)
{
return array($this, $method);
}
/**
* Adds an `ORDER BY` clause to the SQL for the primary keys of this record set
*
* @param fDatabase $db The database the query will be executed on
* @param fSchema $schema The schema for the database
* @param array $params The parameters for the fDatabase::query() call
* @param string $related_class The related class to add the order bys for
* @param string $route The route to this table from another table
* @return array The params with the `ORDER BY` clause added
*/
private function addOrderByParams($db, $schema, $params, $related_class, $route=NULL)
{
$table = fORM::tablize($this->class);
$table_with_route = ($route) ? $table . '{' . $route . '}' : $table;
$pk_columns = $schema->getKeys($table, 'primary');
$first_pk_column = $pk_columns[0];
$escaped_pk_columns = array();
foreach ($pk_columns as $pk_column) {
$escaped_pk_columns[$pk_column] = $db->escape('%r', $table_with_route . '.' . $pk_column);
}
$column_info = $schema->getColumnInfo($table);
$sql = '';
$number = 0;
foreach ($this->getPrimaryKeys() as $primary_key) {
$sql .= 'WHEN ';
if (is_array($primary_key)) {
$conditions = array();
foreach ($pk_columns as $pk_column) {
$value = $primary_key[$pk_column];
// This makes sure the query performs the way an insert will
if ($value === NULL && $column_info[$pk_column]['not_null'] && $column_info[$pk_column]['default'] !== NULL) {
$value = $column_info[$pk_column]['default'];
}
$conditions[] = str_replace(
'%r',
$escaped_pk_columns[$pk_column],
fORMDatabase::makeCondition($schema, $table, $pk_column, '=', $value)
);
$params[] = $value;
}
$sql .= join(' AND ', $conditions);
} else {
$sql .= str_replace(
'%r',
$escaped_pk_columns[$first_pk_column],
fORMDatabase::makeCondition($schema, $table, $first_pk_column, '=', $primary_key)
);
$params[] = $primary_key;
}
$sql .= ' THEN ' . $number . ' ';
$number++;
}
$params[0] .= 'CASE ' . $sql . 'END ASC';
if ($related_order_bys = fORMRelated::getOrderBys($this->class, $related_class, $route)) {
$params[0] .= ', ';
$params = fORMDatabase::addOrderByClause($db, $schema, $params, fORM::tablize($related_class), $related_order_bys);
}
return $params;
}
/**
* Adds `WHERE` params to the SQL for the primary keys of this record set
*
* @param fDatabase $db The database the query will be executed on
* @param fSchema $schema The schema for the database
* @param array $params The parameters for the fDatabase::query() call
* @param string $route The route to this table from another table
* @return array The params with the `WHERE` clause added
*/
private function addWhereParams($db, $schema, $params, $route=NULL)
{
$table = fORM::tablize($this->class);
$table_with_route = ($route) ? $table . '{' . $route . '}' : $table;
$pk_columns = $schema->getKeys($table, 'primary');
// We have a multi-field primary key, making things kinda ugly
if (sizeof($pk_columns) > 1) {
$escape_pk_columns = array();
foreach ($pk_columns as $pk_column) {
$escaped_pk_columns[$pk_column] = $db->escape('%r', $table_with_route . '.' . $pk_column);
}
$column_info = $schema->getColumnInfo($table);
$conditions = array();
foreach ($this->getPrimaryKeys() as $primary_key) {
$sub_conditions = array();
foreach ($pk_columns as $pk_column) {
$value = $primary_key[$pk_column];
// This makes sure the query performs the way an insert will
if ($value === NULL && $column_info[$pk_column]['not_null'] && $column_info[$pk_column]['default'] !== NULL) {
$value = $column_info[$pk_column]['default'];
}
$sub_conditions[] = str_replace(
'%r',
$escaped_pk_columns[$pk_column],
fORMDatabase::makeCondition($schema, $table, $pk_column, '=', $value)
);
$params[] = $value;
}
$conditions[] = join(' AND ', $sub_conditions);
}
$params[0] .= '(' . join(') OR (', $conditions) . ')';
// We have a single primary key field, making things nice and easy
} else {
$first_pk_column = $pk_columns[0];
$params[0] .= $db->escape('%r IN ', $table_with_route . '.' . $first_pk_column);
$params[0] .= '(' . $schema->getColumnInfo($table, $first_pk_column, 'placeholder') . ')';
$params[] = $this->getPrimaryKeys();
}
return $params;
}
/**
* Calls a specific method on each object, returning an fRecordSet of the results
*
* @param string $method The method to call
* @param mixed $parameter A parameter to pass for each call to the method
* @param mixed ...
* @return fRecordSet A set of records that resulted from calling the method
*/
public function buildFromCall($method)
{
$parameters = func_get_args();
$result = call_user_func_array($this->call, $parameters);
$classes = array();
foreach ($result as $record) {
if (!$record instanceof fActiveRecord) {
throw new fProgrammerException(
'The method called, %1$s, returned something other than an fActiveRecord object',
$method
);
}
$class = get_class($record);
if (!isset($classes[$class])) {
$classes[$class] = TRUE;
}
}
// If no objects were returned we need to fake the class
if (!$classes) {
$classes = array('fActiveRecord' => TRUE);
}
return new fRecordSet(array_keys($classes), $result);
}
/**
* Maps each record in the set to a callback function, returning an fRecordSet of the results
*
* @param callback $callback The callback to pass the values to
* @param mixed $parameter The parameter to pass to the callback - see method description for details
* @param mixed ...
* @return fRecordSet A set of records that resulted from the mapping operation
*/
public function buildFromMap($callback)
{
$parameters = func_get_args();
$result = call_user_func_array($this->map, $parameters);
$classes = array();
foreach ($result as $record) {
if (!$record instanceof fActiveRecord) {
throw new fProgrammerException(
'The map operation specified, %1$s, returned something other than an fActiveRecord object',
$callback
);
}
$class = get_class($record);
if (!isset($classes[$class])) {
$classes[$class] = TRUE;
}
}
// If no objects were returned we need to fake the class
if (!$classes) {
$classes = array('fActiveRecord' => TRUE);
}
return new fRecordSet(array_keys($classes), $result);
}
/**
* Calls a specific method on each object, returning an array of the results
*
* @param string $method The method to call
* @param mixed $parameter A parameter to pass for each call to the method
* @param mixed ...
* @return array An array the size of the record set with one result from each record/method
*/
public function call($method)
{
$parameters = array_slice(func_get_args(), 1);
$output = array();
foreach ($this->records as $record) {
$output[] = call_user_func_array(
$record->$method,
$parameters
);
}
return $output;
}
/**
* Chunks the record set into an array of fRecordSet objects
*
* Each fRecordSet would contain `$number` records, except for the last,
* which will contain between 1 and `$number` records.
*
* @param integer $number The number of fActiveRecord objects to place in each fRecordSet
* @return array An array of fRecordSet objects
*/
public function chunk($number)
{
$output = array();
$number_of_sets = ceil($this->count()/$number);
for ($i=0; $i < $number_of_sets; $i++) {
$output[] = new fRecordSet($this->class, array_slice($this->records, $i*$number, $number));
}
return $output;
}
/**
* Checks if the record set contains the record specified
*
* @param fActiveRecord $record The record to check, must exist in the database
* @return boolean If the record specified is in this record set
*/
public function contains($record)
{
$class = get_class($record);
if (!in_array($class, (array) $this->class)) {
return FALSE;
}
if (!$record->exists()) {
throw new fProgrammerException(
'Only records that exist can be checked for in the record set'
);
}
$hash = fActiveRecord::hash($record);
foreach ($this->records as $_record) {
if ($class != get_class($_record)) {
continue;
}
if ($hash == fActiveRecord::hash($_record)) {
return TRUE;
}
}
return FALSE;
}
/**
* Returns the number of records in the set
*
* @param boolean $ignore_limit If set to `TRUE`, this method will return the number of records that would be in the set if there was no `LIMIT` clause
* @return integer The number of records in the set
*/
public function count($ignore_limit=FALSE)
{
if ($ignore_limit !== TRUE || $this->non_limited_count === NULL) {
return sizeof($this->records);
}
if (!is_numeric($this->non_limited_count)) {
try {
$db = fORMDatabase::retrieve($this->class, 'read');
// The integer cast here is to solve issues with the broken dblib
// SQL Server driver that is sometimes present on Windows machines
$this->non_limited_count = (integer) $db->translatedQuery($this->non_limited_count)->fetchScalar();
} catch (fExpectedException $e) {
$this->non_limited_count = $this->count();
}
}
return $this->non_limited_count;
}
/**
* Removes all passed records from the current record set
*
* @param fRecordSet|array|fActiveRecord $records The record set, array of records, or record to remove from the current record set, all instances will be removed
* @param boolean $remember_original_count If the number of records in the current set should be saved as the non-limited count for the new set - the page will be reset to `1` either way
* @return fRecordSet The records not present in the passed records
*/
public function diff($records, $remember_original_count=FALSE)
{
$remove_records = array();
if ($records instanceof fActiveRecord) {
$records = array($records);
}
foreach ($records as $record) {
$class = get_class($record);
$hash = fActiveRecord::hash($record);
$remove_records[$class . '::' . $hash] = TRUE;
}
$new_records = array();
$classes = array();
foreach ($this->records as $record) {
$class = get_class($record);
$hash = fActiveRecord::hash($record);
if (!isset($remove_records[$class . '::' . $hash])) {
$new_records[] = $record;
$classes[$class] = TRUE;
}
}
if ($classes) {
$class = array_keys($classes);
} else {
$class = $this->class;
}
return new fRecordSet(
$class,
$new_records,
$remember_original_count ? $this->count() : NULL
);
}
/**
* Filters the records in the record set via a callback
*
* The `$callback` parameter can be one of three different forms to filter
* the records in the set: