-
Notifications
You must be signed in to change notification settings - Fork 78
/
fActiveRecord.php
3064 lines (2560 loc) · 97.5 KB
/
fActiveRecord.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
/**
* An [http://en.wikipedia.org/wiki/Active_record_pattern active record pattern] base class
*
* This class uses fORMSchema to inspect your database and provides an
* OO interface to a single database table. The class dynamically handles
* method calls for getting, setting and other operations on columns. It also
* dynamically handles retrieving and storing related records.
*
* @copyright Copyright (c) 2007-2011 Will Bond, others
* @author Will Bond [wb] <[email protected]>
* @author Will Bond, iMarc LLC [wb-imarc] <[email protected]>
* @author Jeff Turcotte [jt] <[email protected]>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fActiveRecord
*
* @version 1.0.0b83
* @changes 1.0.0b83 Added the `$recursive` parameter to ::populate() [wb, 2011-09-16]
* @changes 1.0.0b82 Added support for registering methods for __callStatic() [jt, 2011-07-25]
* @changes 1.0.0b81 Fixed a bug with updating a record that contains only an auto-incrementing primary key [wb, 2011-09-06]
* @changes 1.0.0b80 Added support to ::checkCondition() for the `^~` and `$~` operators [wb, 2011-06-20]
* @changes 1.0.0b79 Fixed some bugs in handling relationships between PHP 5.3 namespaced classes [wb, 2011-05-26]
* @changes 1.0.0b78 Backwards Compatibility Break - ::reflect() now returns an associative array instead of a string [wb, 2011-05-10]
* @changes 1.0.0b77 Fixed ::inspect() to not throw an fProgrammerException when a valid element has a `NULL` value [wb, 2011-05-10]
* @changes 1.0.0b76 Added ::clearIdentityMap() [wb, 2011-05-09]
* @changes 1.0.0b75 Fixed a bug where child records of a record with a non-auto-incrementing primary key would not be saved properly for a new record [wb, 2010-12-06]
* @changes 1.0.0b74 Updated ::populate() to use the `binary` type for fRequest::get() [wb, 2010-11-30]
* @changes 1.0.0b73 Backwards Compatibility Break - changed column set methods to treat strings of all whitespace the same as empty string and convert them to `NULL` [wb, 2010-11-29]
* @changes 1.0.0b72 Added the new `comment` element to the reflection signature for `inspect` methods [wb, 2010-11-28]
* @changes 1.0.0b71 Updated class to use fORM::getRelatedClass() [wb, 2010-11-24]
* @changes 1.0.0b70 Added support for PHP 5.3 namespaced fActiveRecord classes [wb, 2010-11-11]
* @changes 1.0.0b69 Backwards Compatibility Break - changed ::validate() to return a nested array of validation messages when there are validation errors on child records [wb-imarc+wb, 2010-10-03]
* @changes 1.0.0b68 Added hooks to ::replicate() [wb, 2010-09-07]
* @changes 1.0.0b67 Updated code to work with the new fORM API [wb, 2010-08-06]
* @changes 1.0.0b66 Fixed a bug with ::store() and non-primary key auto-incrementing columns [wb, 2010-07-05]
* @changes 1.0.0b65 Fixed bugs with ::inspect() making some `min_value` and `max_value` elements available for non-numeric types, fixed ::reflect() to list the `min_value` and `max_value` elements [wb, 2010-06-08]
* @changes 1.0.0b64 BackwardsCompatibilityBreak - changed ::validate()'s returned messages array to have field name keys - added the option to ::validate() to remove field names from messages [wb, 2010-05-26]
* @changes 1.0.0b63 Changed how is_subclass_of() is used to work around a bug in 5.2.x [wb, 2010-04-06]
* @changes 1.0.0b62 Fixed a bug that could cause infinite recursion starting in v1.0.0b60 [wb, 2010-04-02]
* @changes 1.0.0b61 Fixed issues with handling `populate` actions when working with mapped classes [wb, 2010-03-31]
* @changes 1.0.0b60 Fixed issues with handling `associate` and `has` actions when working with mapped classes, added ::validateClass() [wb, 2010-03-30]
* @changes 1.0.0b59 Changed an extended UTF-8 arrow character into the correct `->` [wb, 2010-03-29]
* @changes 1.0.0b58 Fixed ::reflect() to specify the value returned from `set` methods [wb, 2010-03-15]
* @changes 1.0.0b57 Added the `post::loadFromIdentityMap()` hook and fixed ::__construct() to always call the `post::__construct()` hook [wb, 2010-03-14]
* @changes 1.0.0b56 Fixed `$force_cascade` in ::delete() to work even when the restricted relationship is once-removed through an unrestricted relationship [wb, 2010-03-09]
* @changes 1.0.0b55 Fixed ::load() to that related records are cleared, requiring them to be loaded from the database [wb, 2010-03-04]
* @changes 1.0.0b54 Fixed detection of route name for one-to-one relationships in ::delete() [wb, 2010-03-03]
* @changes 1.0.0b53 Fixed a bug where related records with a primary key that contained a foreign key with an on update cascade clause would be deleted when changing the value of the column referenced by the foreign key [wb, 2009-12-17]
* @changes 1.0.0b52 Backwards Compatibility Break - Added the $force_cascade parameter to ::delete() and ::store() - enabled calling ::prepare() and ::encode() for non-column get methods, added `::has{RelatedRecords}()` methods [wb, 2009-12-16]
* @changes 1.0.0b51 Made ::changed() properly recognize that a blank string and NULL are equivalent due to the way that ::set() casts values [wb, 2009-11-14]
* @changes 1.0.0b50 Fixed a bug with trying to load by a multi-column primary key where one of the columns was not specified [wb, 2009-11-13]
* @changes 1.0.0b49 Fixed a bug affecting where conditions with columns that are not null but have a default value [wb, 2009-11-03]
* @changes 1.0.0b48 Updated code for the new fORMDatabase and fORMSchema APIs [wb, 2009-10-28]
* @changes 1.0.0b47 Changed `::associate{RelatedRecords}()`, `::link{RelatedRecords}()` and `::populate{RelatedRecords}()` to allow for method chaining [wb, 2009-10-22]
* @changes 1.0.0b46 Changed SQL statements to use value placeholders and identifier escaping [wb, 2009-10-22]
* @changes 1.0.0b45 Added support for `!~`, `&~`, `><` and OR comparisons to ::checkConditions(), made object handling in ::checkConditions() more robust [wb, 2009-09-21]
* @changes 1.0.0b44 Updated code for new fValidationException API [wb, 2009-09-18]
* @changes 1.0.0b43 Updated code for new fRecordSet API [wb, 2009-09-16]
* @changes 1.0.0b42 Corrected a grammar bug in ::hash() [wb, 2009-09-09]
* @changes 1.0.0b41 Fixed a bug in the last version that would cause issues with classes containing a custom class to table mapping [wb, 2009-09-01]
* @changes 1.0.0b40 Added a check to the configuration part of ::__construct() to ensure modelled tables have primary keys [wb, 2009-08-26]
* @changes 1.0.0b39 Changed `set{ColumnName}()` methods to return the record for method chaining, fixed a bug with loading by multi-column unique constraints, fixed a bug with ::load() [wb, 2009-08-26]
* @changes 1.0.0b38 Updated ::changed() to do a strict comparison when at least one value is NULL [wb, 2009-08-17]
* @changes 1.0.0b37 Changed ::__construct() to allow any Iterator object instead of just fResult [wb, 2009-08-12]
* @changes 1.0.0b36 Fixed a bug with setting NULL values from v1.0.0b33 [wb, 2009-08-10]
* @changes 1.0.0b35 Fixed a bug with unescaping data in ::loadFromResult() from v1.0.0b33 [wb, 2009-08-10]
* @changes 1.0.0b34 Added the ability to compare fActiveRecord objects in ::checkConditions() [wb, 2009-08-07]
* @changes 1.0.0b33 Performance enhancements to ::__call() and ::__construct() [wb, 2009-08-07]
* @changes 1.0.0b32 Changed ::delete() to remove auto-incrementing primary keys after the post::delete() hook [wb, 2009-07-29]
* @changes 1.0.0b31 Fixed a bug with loading a record by a multi-column primary key, fixed one-to-one relationship API [wb, 2009-07-21]
* @changes 1.0.0b30 Updated ::reflect() for new fORM::callReflectCallbacks() API [wb, 2009-07-13]
* @changes 1.0.0b29 Updated to use new fORM::callInspectCallbacks() method [wb, 2009-07-13]
* @changes 1.0.0b28 Fixed a bug where records would break the identity map at the end of ::store() [wb, 2009-07-09]
* @changes 1.0.0b27 Changed ::hash() from a protected method to a static public/internal method that requires the class name for non-fActiveRecord values [wb, 2009-07-09]
* @changes 1.0.0b26 Added ::checkConditions() from fRecordSet [wb, 2009-07-08]
* @changes 1.0.0b25 Updated ::validate() to use new fORMValidation API, including new message search/replace functionality [wb, 2009-07-01]
* @changes 1.0.0b24 Changed ::validate() to remove duplicate validation messages [wb, 2009-06-30]
* @changes 1.0.0b23 Updated code for new fORMValidation::validateRelated() API [wb, 2009-06-26]
* @changes 1.0.0b22 Added support for the $formatting parameter to encode methods on char, text and varchar columns [wb, 2009-06-19]
* @changes 1.0.0b21 Performance tweaks and updates for fORM and fORMRelated API changes [wb, 2009-06-15]
* @changes 1.0.0b20 Changed replacement values in preg_replace() calls to be properly escaped [wb, 2009-06-11]
* @changes 1.0.0b19 Added `list{RelatedRecords}()` methods, updated code for new fORMRelated API [wb, 2009-06-02]
* @changes 1.0.0b18 Changed ::store() to use new fORMRelated::store() method [wb, 2009-06-02]
* @changes 1.0.0b17 Added some missing parameter information to ::reflect() [wb, 2009-06-01]
* @changes 1.0.0b16 Fixed bugs in ::__clone() and ::replicate() related to recursive relationships [wb-imarc, 2009-05-20]
* @changes 1.0.0b15 Fixed an incorrect variable reference in ::store() [wb, 2009-05-06]
* @changes 1.0.0b14 ::store() no longer tries to get an auto-incrementing ID from the database if a value was set [wb, 2009-05-02]
* @changes 1.0.0b13 ::delete(), ::load(), ::populate() and ::store() now return the record to allow for method chaining [wb, 2009-03-23]
* @changes 1.0.0b12 ::set() now removes commas from integers and floats to prevent validation issues [wb, 2009-03-22]
* @changes 1.0.0b11 ::encode() no longer adds commas to floats [wb, 2009-03-22]
* @changes 1.0.0b10 ::__wakeup() no longer registers the record as the definitive copy in the identity map [wb, 2009-03-22]
* @changes 1.0.0b9 Changed ::__construct() to populate database default values when a non-existing record is instantiated [wb, 2009-01-12]
* @changes 1.0.0b8 Fixed ::exists() to properly detect cases when an existing record has one or more NULL values in the primary key [wb, 2009-01-11]
* @changes 1.0.0b7 Fixed ::__construct() to not trigger the post::__construct() hook when force-configured [wb, 2008-12-30]
* @changes 1.0.0b6 ::__construct() now accepts an associative array matching any unique key or primary key, fixed the post::__construct() hook to be called once for each record [wb, 2008-12-26]
* @changes 1.0.0b5 Fixed ::replicate() to use plural record names for related records [wb, 2008-12-12]
* @changes 1.0.0b4 Added ::replicate() to allow cloning along with related records [wb, 2008-12-12]
* @changes 1.0.0b3 Changed ::__clone() to clone objects contains in the values and cache arrays [wb, 2008-12-11]
* @changes 1.0.0b2 Added the ::__clone() method to properly duplicate a record [wb, 2008-12-04]
* @changes 1.0.0b The initial implementation [wb, 2007-08-04]
*/
abstract class fActiveRecord
{
// The following constants allow for nice looking callbacks to static methods
const assign = 'fActiveRecord::assign';
const changed = 'fActiveRecord::changed';
const checkConditions = 'fActiveRecord::checkConditions';
const forceConfigure = 'fActiveRecord::forceConfigure';
const hasOld = 'fActiveRecord::hasOld';
const reset = 'fActiveRecord::reset';
const retrieveOld = 'fActiveRecord::retrieveOld';
const validateClass = 'fActiveRecord::validateClass';
/**
* Caches callbacks for methods
*
* @var array
*/
static protected $callback_cache = array();
/**
* An array of flags indicating a class has been configured
*
* @var array
*/
static protected $configured = array();
/**
* Maps objects via their primary key
*
* @var array
*/
static protected $identity_map = array();
/**
* Caches method name parsings
*
* @var array
*/
static protected $method_name_cache = array();
/**
* Keeps track of the recursive call level of replication so we can clear the map
*
* @var integer
*/
static protected $replicate_level = 0;
/**
* Keeps a list of records that have been replicated
*
* @var array
*/
static protected $replicate_map = array();
/**
* Caches callbacks for static methods
*
* @var array
**/
static protected $static_callback_cache = array();
/**
* Contains a list of what columns in each class need to be unescaped and what data type they are
*
* @var array
*/
static protected $unescape_map = array();
/**
* Handles dynamically registered static method callbacks
*
* Static method callbacks registered through fORM::registerActiveRecordStaticMethod()
* will be delegated via this method. Both this and fORM::registerActiveRecordStaticMethod
* are available to PHP 5.3+ only.
*
* @throws fProgrammerException When the method cannot be found
* @param string $method_name The name of the method called
* @param array $parameters The parameters passed
* @return mixed The value returned by the method called
*/
static public function __callStatic($method_name, $parameters)
{
$class = get_called_class();
self::forceConfigure($class);
if (!isset(self::$static_callback_cache[$class][$method_name])) {
if (!isset(self::$static_callback_cache[$class])) {
self::$static_callback_cache[$class] = array();
}
$callback = fORM::getActiveRecordStaticMethod($class, $method_name);
self::$static_callback_cache[$class][$method_name] = $callback ? $callback : FALSE;
}
if ($callback = self::$static_callback_cache[$class][$method_name]) {
return call_user_func_array(
$callback,
array(
$class,
$method_name,
$parameters
)
);
}
// Error handler
throw new fProgrammerException(
'Unknown static method, %s(), called',
$method_name
);
}
/**
* Sets a value to the `$values` array, preserving the old value in `$old_values`
*
* @internal
*
* @param array &$values The current values
* @param array &$old_values The old values
* @param string $column The column to set
* @param mixed $value The value to set
* @return void
*/
static public function assign(&$values, &$old_values, $column, $value)
{
if (!isset($old_values[$column])) {
$old_values[$column] = array();
}
$old_values[$column][] = $values[$column];
$values[$column] = $value;
}
/**
* Checks to see if a value has changed
*
* @internal
*
* @param array &$values The current values
* @param array &$old_values The old values
* @param string $column The column to check
* @return boolean If the value for the column specified has changed
*/
static public function changed(&$values, &$old_values, $column)
{
if (!isset($old_values[$column])) {
return FALSE;
}
$oldest_value = $old_values[$column][0];
$new_value = $values[$column];
// We do a strict comparison when one of the values is NULL since
// NULL is almost always meant to be distinct from 0, FALSE, etc.
// However, since we cast blank strings to NULL in ::set() but a blank
// string could come out of the database, we consider them to be
// equivalent, so we don't do a strict comparison
if (($oldest_value === NULL && $new_value !== '') || ($new_value === NULL && $oldest_value !== '')) {
return $oldest_value !== $new_value;
}
return $oldest_value != $new_value;
}
/**
* Ensures a class extends fActiveRecord
*
* @internal
*
* @param string $class The class to check
* @return boolean If the class is an fActiveRecord descendant
*/
static public function checkClass($class)
{
if (isset(self::$configured[$class])) {
return TRUE;
}
if (!is_string($class) || !$class || !class_exists($class) || !($class == 'fActiveRecord' || is_subclass_of($class, 'fActiveRecord'))) {
return FALSE;
}
return TRUE;
}
/**
* Checks to see if a record matches a condition
*
* @internal
*
* @param string $operator The record to check
* @param mixed $value The value to compare to
* @param mixed $result The result of the method call(s)
* @return boolean If the comparison was successful
*/
static private function checkCondition($operator, $value, $result)
{
$was_array = is_array($value);
if (!$was_array) { $value = array($value); }
foreach ($value as $i => $_value) {
if (is_object($_value)) {
if ($_value instanceof fActiveRecord) {
continue;
}
if (method_exists($_value, '__toString')) {
$value[$i] = $_value->__toString();
}
}
}
if (!$was_array) { $value = $value[0]; }
$was_array = is_array($result);
if (!$was_array) { $result = array($result); }
foreach ($result as $i => $_result) {
if (is_object($_result)) {
if ($_result instanceof fActiveRecord) {
continue;
}
if (method_exists($_result, '__toString')) {
$result[$i] = $_result->__toString();
}
}
}
if (!$was_array) { $result = $result[0]; }
if ($operator == '~' && !is_array($value) && is_array($result)) {
$value = fORMDatabase::parseSearchTerms($value, TRUE);
}
if (in_array($operator, array('~', '&~', '!~', '^~', '$~'))) {
settype($value, 'array');
settype($result, 'array');
}
switch ($operator) {
case '&~':
foreach ($value as $_value) {
if (fUTF8::ipos($result[0], $_value) === FALSE) {
return FALSE;
}
}
break;
case '~':
// Handles fuzzy search on multiple method calls
if (count($result) > 1) {
foreach ($value as $_value) {
$found = FALSE;
foreach ($result as $_result) {
if (fUTF8::ipos($_result, $_value) !== FALSE) {
$found = TRUE;
}
}
if (!$found) {
return FALSE;
}
}
break;
}
// No break exists since a ~ on a single method call acts
// similar to the other LIKE operators
case '!~':
case '^~':
case '$~':
if ($operator == '$~') {
$result_len = fUTF8::len($result[0]);
}
foreach ($value as $_value) {
$pos = fUTF8::ipos($result[0], $_value);
if ($operator == '^~' && $pos === 0) {
return TRUE;
} elseif ($operator == '$~' && $pos === $result_len - fUTF8::len($_value)) {
return TRUE;
} elseif ($pos !== FALSE) {
return $operator != '!~';
}
}
if ($operator != '!~') {
return FALSE;
}
break;
case '=':
if ($value instanceof fActiveRecord && $result instanceof fActiveRecord) {
if (get_class($value) != get_class($result) || !$value->exists() || !$result->exists() || self::hash($value) != self::hash($result)) {
return FALSE;
}
} elseif (is_array($value) && !in_array($result, $value)) {
return FALSE;
} elseif (!is_array($value) && $result != $value) {
return FALSE;
}
break;
case '!':
if ($value instanceof fActiveRecord && $result instanceof fActiveRecord) {
if (get_class($value) == get_class($result) && $value->exists() && $result->exists() && self::hash($value) == self::hash($result)) {
return FALSE;
}
} elseif (is_array($value) && in_array($result, $value)) {
return FALSE;
} elseif (!is_array($value) && $result == $value) {
return FALSE;
}
break;
case '<':
if ($result >= $value) {
return FALSE;
}
break;
case '<=':
if ($result > $value) {
return FALSE;
}
break;
case '>':
if ($result <= $value) {
return FALSE;
}
break;
case '>=':
if ($result < $value) {
return FALSE;
}
break;
}
return TRUE;
}
/**
* Checks to see if a record matches all of the conditions
*
* @internal
*
* @param fActiveRecord $record The record to check
* @param array $conditions The conditions to check - see fRecordSet::filter() for format details
* @return boolean If the record meets all conditions
*/
static public function checkConditions($record, $conditions)
{
foreach ($conditions as $method => $value) {
// Split the operator off of the end of the method name
if (in_array(substr($method, -2), array('<=', '>=', '!=', '<>', '!~', '&~', '^~', '$~', '><'))) {
$operator = strtr(
substr($method, -2),
array(
'<>' => '!',
'!=' => '!'
)
);
$method = substr($method, 0, -2);
} else {
$operator = substr($method, -1);
$method = substr($method, 0, -1);
}
if (preg_match('#(?<!\|)\|(?!\|)#', $method)) {
$methods = explode('|', $method);
$values = $value;
$operators = array();
foreach ($methods as &$_method) {
if (in_array(substr($_method, -2), array('<=', '>=', '!=', '<>', '!~', '&~', '^~', '$~', '><'))) {
$operators[] = strtr(
substr($_method, -2),
array(
'<>' => '!',
'!=' => '!'
)
);
$_method = substr($_method, 0, -2);
} elseif (!ctype_alnum(substr($_method, -1))) {
$operators[] = substr($_method, -1);
$_method = substr($_method, 0, -1);
}
}
$operators[] = $operator;
if (sizeof($operators) == 1) {
// Handle fuzzy searches
if ($operator == '~') {
$results = array();
foreach ($methods as $method) {
$results[] = $record->$method();
}
if (!self::checkCondition($operator, $value, $results)) {
return FALSE;
}
// Handle intersection
} elseif ($operator == '><') {
if (sizeof($methods) != 2 || sizeof($values) != 2) {
throw new fProgrammerException(
'The intersection operator, %s, requires exactly two methods and two values',
$operator
);
}
$results = array();
$results[0] = $record->{$methods[0]}();
$results[1] = $record->{$methods[1]}();
if ($results[1] === NULL && $values[1] === NULL) {
if (!self::checkCondition('=', $values[0], $results[0])) {
return FALSE;
}
} else {
$starts_between_values = FALSE;
$overlaps_value_1 = FALSE;
if ($values[1] !== NULL) {
$start_lt_value_1 = self::checkCondition('<', $values[0], $results[0]);
$start_gt_value_2 = self::checkCondition('>', $values[1], $results[0]);
$starts_between_values = !$start_lt_value_1 && !$start_gt_value_2;
}
if ($results[1] !== NULL) {
$start_gt_value_1 = self::checkCondition('>', $values[0], $results[0]);
$end_lt_value_1 = self::checkCondition('<', $values[0], $results[1]);
$overlaps_value_1 = !$start_gt_value_1 && !$end_lt_value_1;
}
if (!$starts_between_values && !$overlaps_value_1) {
return FALSE;
}
}
} else {
throw new fProgrammerException(
'An invalid comparison operator, %s, was specified for multiple columns',
$operator
);
}
// Handle OR conditions
} else {
if (sizeof($methods) != sizeof($values)) {
throw new fProgrammerException(
'When performing an %1$s comparison there must be an equal number of methods and values, however there are not',
'OR',
sizeof($methods),
sizeof($values)
);
}
if (sizeof($methods) != sizeof($operators)) {
throw new fProgrammerException(
'When performing an %s comparison there must be a comparison operator for each column, however one or more is missing',
'OR'
);
}
$results = array();
$iterations = sizeof($methods);
for ($i=0; $i<$iterations; $i++) {
$results[] = self::checkCondition($operators[$i], $values[$i], $record->{$methods[$i]}());
}
if (!array_filter($results)) {
return FALSE;
}
}
// Single method comparisons
} else {
$result = $record->$method();
if (!self::checkCondition($operator, $value, $result)) {
return FALSE;
}
}
}
return TRUE;
}
/**
* Clears the identity map
*
* @return void
*/
static public function clearIdentityMap()
{
self::$identity_map = array();
}
/**
* 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);
}
}
/**
* Takes information from a method call and determines the subject, route and if subject was plural
*
* @param string $class The class the method was called on
* @param string $subject An underscore_notation subject - either a singular or plural class name
* @param string $route The route to the subject
* @return array An array with the structure: array(0 => $subject, 1 => $route, 2 => $plural)
*/
static private function determineSubject($class, $subject, $route)
{
$schema = fORMSchema::retrieve($class);
$table = fORM::tablize($class);
$type = '*-to-many';
$plural = FALSE;
// one-to-many relationships need to use plural forms
$singular_form = fGrammar::singularize($subject, TRUE);
if ($singular_form && fORM::isClassMappedToTable($singular_form)) {
$subject = $singular_form;
$plural = TRUE;
} elseif (!fORM::isClassMappedToTable($subject) && in_array(fGrammar::underscorize($subject), $schema->getTables())) {
$subject = fGrammar::singularize($subject);
$plural = TRUE;
}
$related_table = fORM::tablize($subject);
$one_to_one = fORMSchema::isOneToOne($schema, $table, $related_table, $route);
if ($one_to_one) {
$type = 'one-to-one';
}
if (($one_to_one && $plural) || (!$plural && !$one_to_one)) {
throw new fProgrammerException(
'The table %1$s is not in a %2$srelationship with the table %3$s',
$table,
$type,
$related_table
);
}
$route = fORMSchema::getRouteName($schema, $table, $related_table, $route, $type);
return array($subject, $route, $plural);
}
/**
* Ensures that ::configure() has been called for the class
*
* @internal
*
* @param string $class The class to configure
* @return void
*/
static public function forceConfigure($class)
{
if (isset(self::$configured[$class])) {
return;
}
new $class();
}
/**
* Takes a row of data or a primary key and makes a hash from the primary key
*
* @internal
*
* @param fActiveRecord|array|string|int $record An fActiveRecord object, an array of the records data, an array of primary key data or a scalar primary key value
* @param string $class The class name, if $record isn't an fActiveRecord
* @return string|NULL A hash of the record's primary key value or NULL if the record doesn't exist yet
*/
static public function hash($record, $class=NULL)
{
if ($record instanceof fActiveRecord && !$record->exists()) {
return NULL;
}
if ($class === NULL) {
if (!$record instanceof fActiveRecord) {
throw new fProgrammerException(
'The class of the record must be provided if the record specified is not an instance of fActiveRecord'
);
}
$class = get_class($record);
}
$schema = fORMSchema::retrieve($class);
$table = fORM::tablize($class);
$pk_columns = $schema->getKeys($table, 'primary');
// Build an array of just the primary key data
$pk_data = array();
foreach ($pk_columns as $pk_column) {
if ($record instanceof fActiveRecord) {
$value = (self::hasOld($record->old_values, $pk_column)) ? self::retrieveOld($record->old_values, $pk_column) : $record->values[$pk_column];
} elseif (is_array($record)) {
$value = $record[$pk_column];
} else {
$value = $record;
}
$pk_data[$pk_column] = fORM::scalarize(
$class,
$pk_column,
$value
);
if (is_numeric($pk_data[$pk_column]) || is_object($pk_data[$pk_column])) {
$pk_data[$pk_column] = (string) $pk_data[$pk_column];
}
}
return md5(serialize($pk_data));
}
/**
* Checks to see if an old value exists for a column
*
* @internal
*
* @param array &$old_values The old values
* @param string $column The column to set
* @return boolean If an old value for that column exists
*/
static public function hasOld(&$old_values, $column)
{
return array_key_exists($column, $old_values);
}
/**
* Resets the configuration of the class
*
* @internal
*
* @return void
*/
static public function reset()
{
self::$callback_cache = array();
self::$configured = array();
self::$identity_map = array();
self::$method_name_cache = array();
self::$unescape_map = array();
}
/**
* Retrieves the oldest value for a column or all old values
*
* @internal
*
* @param array &$old_values The old values
* @param string $column The column to get
* @param mixed $default The default value to return if no value exists
* @param boolean $return_all Return the array of all old values for this column instead of just the oldest
* @return mixed The old value for the column
*/
static public function retrieveOld(&$old_values, $column, $default=NULL, $return_all=FALSE)
{
if (!isset($old_values[$column])) {
return $default;
}
if ($return_all === TRUE) {
return $old_values[$column];
}
return $old_values[$column][0];
}
/**
* Ensures a class extends fActiveRecord
*
* @internal
*
* @param string $class The class to verify
* @return void
*/
static public function validateClass($class)
{
if (isset(self::$configured[$class])) {
return TRUE;
}
if (!self::checkClass($class)) {
throw new fProgrammerException(
'The class specified, %1$s, does not appear to be a valid %2$s class',
$class,
'fActiveRecord'
);
}
}
/**
* A data store for caching data related to a record, the structure of this is completely up to the developer using it
*
* @var array
*/
protected $cache = array();
/**
* The old values for this record
*
* Column names are the keys, but a column key will only be present if a
* value has changed. The value associated with each key is an array of
* old values with the first entry being the oldest value. The static
* methods ::assign(), ::changed(), ::hasOld() and ::retrieveOld() are the
* best way to interact with this array.
*
* @var array
*/
protected $old_values = array();
/**
* Records that are related to the current record via some relationship
*
* This array is used to cache related records so that a database query
* is not required each time related records are accessed. The fORMRelated
* class handles most of the interaction with this array.
*
* @var array
*/
protected $related_records = array();
/**
* The values for this record
*
* This array always contains every column in the database table as a key
* with the value being the current value.
*
* @var array
*/
protected $values = array();
/**
* Handles all method calls for columns, related records and hook callbacks
*
* Dynamically handles `get`, `set`, `prepare`, `encode` and `inspect`
* methods for each column in this record. Method names are in the form
* `verbColumName()`.
*
* This method also handles `associate`, `build`, `count`, `has`, and `link`
* verbs for records in many-to-many relationships; `build`, `count`, `has`
* and `populate` verbs for all related records in one-to-many relationships
* and `create`, `has` and `populate` verbs for all related records in
* one-to-one relationships, and the `create` verb for all related records
* in many-to-one relationships.
*
* Method callbacks registered through fORM::registerActiveRecordMethod()
* will be delegated via this method.
*
* @param string $method_name The name of the method called
* @param array $parameters The parameters passed
* @return mixed The value returned by the method called
*/
public function __call($method_name, $parameters)
{
$class = get_class($this);
if (!isset(self::$callback_cache[$class][$method_name])) {
if (!isset(self::$callback_cache[$class])) {
self::$callback_cache[$class] = array();
}
$callback = fORM::getActiveRecordMethod($class, $method_name);
self::$callback_cache[$class][$method_name] = $callback ? $callback : FALSE;
}
if ($callback = self::$callback_cache[$class][$method_name]) {
return call_user_func_array(
$callback,
array(
$this,
&$this->values,
&$this->old_values,
&$this->related_records,
&$this->cache,
$method_name,
$parameters
)
);
}
if (!isset(self::$method_name_cache[$method_name])) {
list ($action, $subject) = fORM::parseMethod($method_name);
if (in_array($action, array('get', 'encode', 'prepare', 'inspect', 'set'))) {
$subject = fGrammar::underscorize($subject);
} else {
if (in_array($action, array('build', 'count', 'inject', 'link', 'list', 'tally'))) {
$subject = fGrammar::singularize($subject);
}
$subject = fORM::getRelatedClass($class, $subject);
}
self::$method_name_cache[$method_name] = array(
'action' => $action,
'subject' => $subject
);
} else {
$action = self::$method_name_cache[$method_name]['action'];
$subject = self::$method_name_cache[$method_name]['subject'];
}
switch ($action) {
// Value methods
case 'get':
return $this->get($subject);
case 'encode':
if (isset($parameters[0])) {
return $this->encode($subject, $parameters[0]);
}
return $this->encode($subject);
case 'prepare':
if (isset($parameters[0])) {
return $this->prepare($subject, $parameters[0]);
}
return $this->prepare($subject);
case 'inspect':
if (isset($parameters[0])) {
return $this->inspect($subject, $parameters[0]);
}
return $this->inspect($subject);
case 'set':
if (sizeof($parameters) < 1) {
throw new fProgrammerException(
'The method, %s(), requires at least one parameter',
$method_name
);
}
return $this->set($subject, $parameters[0]);
// Related data methods
case 'associate':
if (sizeof($parameters) < 1) {
throw new fProgrammerException(
'The method, %s(), requires at least one parameter',
$method_name
);
}