forked from flourishlib/flourish-classes
-
Notifications
You must be signed in to change notification settings - Fork 10
/
fORMValidation.php
1570 lines (1341 loc) · 49.4 KB
/
fORMValidation.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
/**
* Handles validation for fActiveRecord classes
*
* @copyright Copyright (c) 2007-2012 Will Bond, others
* @author Will Bond [wb] <will@flourishlib.com>
* @author Jeff Turcotte [jt] <jeff.turcotte@gmail.com>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fORMValidation
*
*/
class fORMValidation
{
// The following constants allow for nice looking callbacks to static methods
const addConditionalRule = 'fORMValidation::addConditionalRule';
const addManyToManyRule = 'fORMValidation::addManyToManyRule';
const addOneOrMoreRule = 'fORMValidation::addOneOrMoreRule';
const addOneToManyRule = 'fORMValidation::addOneToManyRule';
const addOnlyOneRule = 'fORMValidation::addOnlyOneRule';
const addRegexReplacement = 'fORMValidation::addRegexReplacement';
const addRegexRule = 'fORMValidation::addRegexRule';
const addRequiredRule = 'fORMValidation::addRequiredRule';
const addStringReplacement = 'fORMValidation::addStringReplacement';
const addValidValuesRule = 'fORMValidation::addValidValuesRule';
const hasValue = 'fORMValidation::hasValue';
const inspect = 'fORMValidation::inspect';
const removeStringReplacement = 'fORMValidation::removeStringReplacement';
const removeRegexReplacement = 'fORMValidation::removeRegexReplacement';
const reorderMessages = 'fORMValidation::reorderMessages';
const replaceMessages = 'fORMValidation::replaceMessages';
const reset = 'fORMValidation::reset';
const setColumnCaseInsensitive = 'fORMValidation::setColumnCaseInsensitive';
const setMessageOrder = 'fORMValidation::setMessageOrder';
const validate = 'fORMValidation::validate';
const validateRelated = 'fORMValidation::validateRelated';
/**
* Columns that should be treated as case insensitive when checking uniqueness
*
* @var array
*/
static private $case_insensitive_columns = array();
/**
* Conditional rules
*
* @var array
*/
static private $conditional_rules = array();
/**
* Ordering rules for messages
*
* @var array
*/
static private $message_orders = array();
/**
* One or more rules
*
* @var array
*/
static private $one_or_more_rules = array();
/**
* Only one rules
*
* @var array
*/
static private $only_one_rules = array();
/**
* Regular expression replacements performed on each message
*
* @var array
*/
static private $regex_replacements = array();
/**
* Rules that require at least one or more *-to-many related records to be associated
*
* @var array
*/
static private $related_one_or_more_rules = array();
/**
* Rules that require a value to match a regular expression
*
* @var array
*/
static private $regex_rules = array();
/**
* Rules that require a value be present in a column even if the database schema doesn't require it
*
* @var array
*/
static private $required_rules = array();
/**
* String replacements performed on each message
*
* @var array
*/
static private $string_replacements = array();
/**
* Valid values rules
*
* @var array
*/
static private $valid_values_rules = array();
/**
* Adds a conditional rule
*
* If a non-empty value is found in one of the `$main_columns`, or if
* specified, a value from the `$conditional_values` array, all of the
* `$conditional_columns` will also be required to have a value.
*
* @param mixed $class The class name or instance of the class this rule applies to
* @param string|array $main_columns The column(s) to check for a value
* @param mixed $conditional_values If `NULL`, any value in the main column will trigger the conditional column(s), otherwise the value must match this scalar value or be present in the array of values
* @param string|array $conditional_columns The column(s) that are to be required
* @return void
*/
static public function addConditionalRule($class, $main_columns, $conditional_values, $conditional_columns)
{
$class = fORM::getClass($class);
if (!isset(self::$conditional_rules[$class])) {
self::$conditional_rules[$class] = array();
}
settype($main_columns, 'array');
settype($conditional_columns, 'array');
if ($conditional_values !== NULL) {
settype($conditional_values, 'array');
}
$rule = array();
$rule['main_columns'] = $main_columns;
$rule['conditional_values'] = $conditional_values;
$rule['conditional_columns'] = $conditional_columns;
self::$conditional_rules[$class][] = $rule;
}
/**
* Add a many-to-many rule that requires at least one related record is associated with the current record
*
* @param mixed $class The class name or instance of the class to add the rule for
* @param string $related_class The name of the related class
* @param string $route The route to the related class
* @return void
*/
static public function addManyToManyRule($class, $related_class, $route=NULL)
{
$class = fORM::getClass($class);
$related_class = fORM::getRelatedClass($class, $related_class);
if (!isset(self::$related_one_or_more_rules[$class])) {
self::$related_one_or_more_rules[$class] = array();
}
if (!isset(self::$related_one_or_more_rules[$class][$related_class])) {
self::$related_one_or_more_rules[$class][$related_class] = array();
}
$route = fORMSchema::getRouteName(
fORMSchema::retrieve($class),
fORM::tablize($class),
fORM::tablize($related_class),
$route,
'many-to-many'
);
self::$related_one_or_more_rules[$class][$related_class][$route] = TRUE;
}
/**
* Adds a one-or-more rule that requires at least one of the columns specified has a value
*
* @param mixed $class The class name or instance of the class the columns exists in
* @param array $columns The columns to check
* @return void
*/
static public function addOneOrMoreRule($class, $columns)
{
$class = fORM::getClass($class);
settype($columns, 'array');
if (!isset(self::$one_or_more_rules[$class])) {
self::$one_or_more_rules[$class] = array();
}
$rule = array();
$rule['columns'] = $columns;
self::$one_or_more_rules[$class][] = $rule;
}
/**
* Add a one-to-many rule that requires at least one related record is associated with the current record
*
* @param mixed $class The class name or instance of the class to add the rule for
* @param string $related_class The name of the related class
* @param string $route The route to the related class
* @return void
*/
static public function addOneToManyRule($class, $related_class, $route=NULL)
{
$class = fORM::getClass($class);
$related_class = fORM::getRelatedClass($class, $related_class);
if (!isset(self::$related_one_or_more_rules[$class])) {
self::$related_one_or_more_rules[$class] = array();
}
if (!isset(self::$related_one_or_more_rules[$class][$related_class])) {
self::$related_one_or_more_rules[$class][$related_class] = array();
}
$route = fORMSchema::getRouteName(
fORMSchema::retrieve($class),
fORM::tablize($class),
fORM::tablize($related_class),
$route,
'one-to-many'
);
self::$related_one_or_more_rules[$class][$related_class][$route] = TRUE;
}
/**
* Add an only-one rule that requires exactly one of the columns must have a value
*
* @param mixed $class The class name or instance of the class the columns exists in
* @param array $columns The columns to check
* @return void
*/
static public function addOnlyOneRule($class, $columns)
{
$class = fORM::getClass($class);
settype($columns, 'array');
if (!isset(self::$only_one_rules[$class])) {
self::$only_one_rules[$class] = array();
}
$rule = array();
$rule['columns'] = $columns;
self::$only_one_rules[$class][] = $rule;
}
/**
* Adds a call to [http://php.net/preg_replace `preg_replace()`] for each message
*
* Regex replacement is done after the `post::validate()` hook, and right
* before the messages are reordered.
*
* If a message is an empty string after replacement, it will be
* removed from the list of messages.
*
* @param mixed $class The class name or instance of the class the columns exists in
* @param string $search The PCRE regex to search for - see http://php.net/pcre for details
* @param string $replace The string to replace with - all $ and \ are used in back references and must be escaped with a \ when meant literally
* @return void
*/
static public function addRegexReplacement($class, $search, $replace)
{
$class = fORM::getClass($class);
if (!isset(self::$regex_replacements[$class])) {
self::$regex_replacements[$class] = array(
'search' => array(),
'replace' => array()
);
}
self::$regex_replacements[$class]['search'][] = $search;
self::$regex_replacements[$class]['replace'][] = $replace;
}
/**
* Adds a rule to validate a column against a PCRE regular expression - the rule is not run if the value is `NULL`
*
* @param mixed $class The class name or instance of the class the columns exists in
* @param string $column The column to match with the regex
* @param string $regex The PCRE regex to match against - see http://php.net/pcre for details
* @param string $message The message to use if the value does not match the regular expression
* @return void
*/
static public function addRegexRule($class, $column, $regex, $message)
{
$class = fORM::getClass($class);
if (!isset(self::$regex_rules[$class])) {
self::$regex_rules[$class] = array();
}
self::$regex_rules[$class][$column] = array(
'regex' => $regex,
'message' => $message
);
}
/**
* Requires that a column have a non-`NULL` value
*
* Before using this method, try setting the database column to `NOT NULL`
* and remove any default value. Such a configuration will trigger the same
* functionality as this method, and will enforce the rule on the database
* level for any other code that queries it.
*
* @param mixed $class The class name or instance of the class the column(s) exists in
* @param array $columns The column or columns to check - each column will require a value
* @return void
*/
static public function addRequiredRule($class, $columns)
{
$class = fORM::getClass($class);
settype($columns, 'array');
if (!isset(self::$required_rules[$class])) {
self::$required_rules[$class] = array();
}
foreach ($columns as $column) {
self::$required_rules[$class][$column] = TRUE;
}
}
/**
* Adds a call to [http://php.net/str_replace `str_replace()`] for each message
*
* String replacement is done after the `post::validate()` hook, and right
* before the messages are reordered.
*
* If a message is an empty string after replacement, it will be
* removed from the list of messages.
*
* @param mixed $class The class name or instance of the class the columns exists in
* @param string $search The string to search for
* @param string $replace The string to replace with
* @return void
*/
static public function addStringReplacement($class, $search, $replace)
{
$class = fORM::getClass($class);
if (!isset(self::$string_replacements[$class])) {
self::$string_replacements[$class] = array(
'search' => array(),
'replace' => array()
);
}
self::$string_replacements[$class]['search'][] = $search;
self::$string_replacements[$class]['replace'][] = $replace;
}
/**
* Restricts a column to having only a value from the list of valid values
*
* Please note that `NULL` values are always allowed, even if not listed in
* the `$valid_values` array, if the column is not set as `NOT NULL`.
*
* This functionality can also be accomplished by added a `CHECK` constraint
* on the column in the database, or using a MySQL `ENUM` data type.
*
* @param mixed $class The class name or instance of the class this rule applies to
* @param string $column The column to validate
* @param array $valid_values The valid values to check - `NULL` values are always allows if the column is not set to `NOT NULL`
* @return void
*/
static public function addValidValuesRule($class, $column, $valid_values)
{
$class = fORM::getClass($class);
if (!isset(self::$valid_values_rules[$class])) {
self::$valid_values_rules[$class] = array();
}
settype($valid_values, 'array');
self::$valid_values_rules[$class][$column] = $valid_values;
fORM::registerInspectCallback($class, $column, self::inspect);
}
/**
* Validates a value against the database schema
*
* @param fSchema $schema The schema object for the object
* @param fActiveRecord $object The instance of the class the column is part of
* @param string $column The column to check
* @param array &$values An associative array of all values going into the row (needs all for multi-field unique constraint checking)
* @param array &$old_values The old values from the record
* @return string An error message for the column specified
*/
static private function checkAgainstSchema($schema, $object, $column, &$values, &$old_values)
{
$class = get_class($object);
$table = fORM::tablize($class);
$info = $schema->getColumnInfo($table, $column);
// Make sure a value is provided for required columns
$schema_not_null = $info['not_null'] && $info['default'] === NULL && $info['auto_increment'] === FALSE;
$rule_not_null = isset(self::$required_rules[$class][$column]);
if ($values[$column] === NULL && ($schema_not_null || $rule_not_null)) {
return self::compose(
'%sPlease enter a value',
fValidationException::formatField(fORM::getColumnName($class, $column))
);
}
$message = self::checkDataType($schema, $class, $column, $values[$column]);
if ($message) { return $message; }
// Make sure a valid value is chosen
if (isset($info['valid_values']) && $values[$column] !== NULL && !in_array($values[$column], $info['valid_values'])) {
return self::compose(
'%1$sPlease choose from one of the following: %2$s',
fValidationException::formatField(fORM::getColumnName($class, $column)),
join(', ', $info['valid_values'])
);
}
// Make sure the value isn't too long
if ($info['type'] == 'varchar' && isset($info['max_length']) && $values[$column] !== NULL && is_string($values[$column]) && fUTF8::len($values[$column]) > $info['max_length']) {
return self::compose(
'%1$sPlease enter a value no longer than %2$s characters',
fValidationException::formatField(fORM::getColumnName($class, $column)),
$info['max_length']
);
}
// Make sure the value is the proper length
if ($info['type'] == 'char' && isset($info['max_length']) && $values[$column] !== NULL && is_string($values[$column]) && fUTF8::len($values[$column]) != $info['max_length']) {
return self::compose(
'%1$sPlease enter exactly %2$s characters',
fValidationException::formatField(fORM::getColumnName($class, $column)),
$info['max_length']
);
}
// Make sure the value fits in the numeric range
if (self::stringlike($values[$column]) && in_array($info['type'], array('integer', 'float')) && $info['min_value'] && $info['max_value'] && ($info['min_value']->gt($values[$column]) || $info['max_value']->lt($values[$column]))) {
return self::compose(
'%1$sPlease enter a number between %2$s and %3$s',
fValidationException::formatField(fORM::getColumnName($class, $column)),
$info['min_value']->__toString(),
$info['max_value']->__toString()
);
}
$message = self::checkForeignKeyConstraints($schema, $class, $column, $values);
if ($message) { return $message; }
}
/**
* Validates against a conditional rule
*
* @param fSchema $schema The schema object for the class specified
* @param string $class The class this rule applies to
* @param array &$values An associative array of all values for the record
* @param array $main_columns The columns to check for a value
* @param array $conditional_values If `NULL`, any value in the main column will trigger the conditional columns, otherwise the value must match one of these
* @param array $conditional_columns The columns that are to be required
* @return array The error messages for the rule specified
*/
static private function checkConditionalRule($schema, $class, &$values, $main_columns, $conditional_values, $conditional_columns)
{
$check_for_missing_values = FALSE;
foreach ($main_columns as $main_column) {
$matches_conditional_value = $conditional_values !== NULL && in_array($values[$main_column], $conditional_values);
$has_some_value = $conditional_values === NULL && strlen((string) $values[$main_column]);
if ($matches_conditional_value || $has_some_value) {
$check_for_missing_values = TRUE;
break;
}
}
if (!$check_for_missing_values) {
return;
}
$table = fORM::tablize($class);
$messages = array();
foreach ($conditional_columns as $conditional_column) {
$default_is_space = $schema->getColumnInfo($table, $conditional_column, 'default') === '';
if ($values[$conditional_column] !== NULL && (!$default_is_space || ($default_is_space && $values[$conditional_column] !== ''))) { continue; }
$messages[$conditional_column] = self::compose(
'%sPlease enter a value',
fValidationException::formatField(fORM::getColumnName($class, $conditional_column))
);
}
if ($messages) {
return $messages;
}
}
/**
* Validates a value against the database data type
*
* @param fSchema $schema The schema object for the class
* @param string $class The class the column is part of
* @param string $column The column to check
* @param mixed $value The value to check
* @return string An error message for the column specified
*/
static private function checkDataType($schema, $class, $column, $value)
{
$table = fORM::tablize($class);
$column_info = $schema->getColumnInfo($table, $column);
if ($value !== NULL) {
switch ($column_info['type']) {
case 'varchar':
case 'char':
case 'text':
case 'blob':
if (!is_string($value) && !is_numeric($value)) {
return self::compose(
'%sPlease enter a string',
fValidationException::formatField(fORM::getColumnName($class, $column))
);
}
break;
case 'integer':
if (!is_numeric($value)) {
return self::compose(
'%sPlease enter a whole number',
fValidationException::formatField(fORM::getColumnName($class, $column))
);
}
break;
case 'float':
if (!is_numeric($value)) {
return self::compose(
'%sPlease enter a number',
fValidationException::formatField(fORM::getColumnName($class, $column))
);
}
break;
case 'timestamp':
try {
new fTimestamp($value);
} catch (fValidationException $e) {
return self::compose(
'%sPlease enter a date/time',
fValidationException::formatField(fORM::getColumnName($class, $column))
);
}
break;
case 'date':
try {
new fDate($value);
} catch (fValidationException $e) {
return self::compose(
'%sPlease enter a date',
fValidationException::formatField(fORM::getColumnName($class, $column))
);
}
break;
case 'time':
try {
new fTime($value);
} catch (fValidationException $e) {
return self::compose(
'%sPlease enter a time',
fValidationException::formatField(fORM::getColumnName($class, $column))
);
}
break;
}
}
}
/**
* Validates values against foreign key constraints
*
* @param fSchema $schema The schema object for the class
* @param string $class The class to check the foreign keys for
* @param string $column The column to check
* @param array &$values The values to check
* @return string An error message for the column specified
*/
static private function checkForeignKeyConstraints($schema, $class, $column, &$values)
{
if ($values[$column] === NULL) {
return;
}
$db = fORMDatabase::retrieve($class, 'read');
$table = fORM::tablize($class);
$foreign_keys = $schema->getKeys($table, 'foreign');
foreach ($foreign_keys AS $foreign_key) {
if ($foreign_key['column'] == $column) {
try {
$params = array(
"SELECT %r FROM %r WHERE " . fORMDatabase::makeCondition($schema, $table, $column, '=', $values[$column]),
$foreign_key['foreign_column'],
$foreign_key['foreign_table'],
$foreign_key['foreign_column'],
$values[$column]
);
$result = call_user_func_array($db->translatedQuery, $params);
$result->tossIfNoRows();
} catch (fNoRowsException $e) {
return self::compose(
'%sThe value specified is invalid',
fValidationException::formatField(fORM::getColumnName($class, $column))
);
}
}
}
}
/**
* Validates against a one-or-more rule
*
* @param fSchema $schema The schema object for the table
* @param string $class The class the columns are part of
* @param array &$values An associative array of all values for the record
* @param array $columns The columns to check
* @return string An error message for the rule
*/
static private function checkOneOrMoreRule($schema, $class, &$values, $columns)
{
settype($columns, 'array');
$found_value = FALSE;
foreach ($columns as $column) {
if (self::hasValue($schema, $class, $values, $column)) {
$found_value = TRUE;
}
}
if (!$found_value) {
$column_names = array();
foreach ($columns as $column) {
$column_names[] = fORM::getColumnName($class, $column);
}
return self::compose(
'%sPlease enter a value for at least one',
fValidationException::formatField(join(', ', $column_names))
);
}
}
/**
* Validates against an only-one rule
*
* @param fSchema $schema The schema object for the table
* @param string $class The class the columns are part of
* @param array &$values An associative array of all values for the record
* @param array $columns The columns to check
* @return string An error message for the rule
*/
static private function checkOnlyOneRule($schema, $class, &$values, $columns)
{
settype($columns, 'array');
$column_names = array();
foreach ($columns as $column) {
$column_names[] = fORM::getColumnName($class, $column);
}
$found_value = FALSE;
foreach ($columns as $column) {
if (self::hasValue($schema, $class, $values, $column)) {
if ($found_value) {
return self::compose(
'%sPlease enter a value for only one',
fValidationException::formatField(join(', ', $column_names))
);
}
$found_value = TRUE;
}
}
if (!$found_value) {
return self::compose(
'%sPlease enter a value for one',
fValidationException::formatField(join(', ', $column_names))
);
}
}
/**
* Makes sure a record with the same primary keys is not already in the database
*
* @param fSchema $schema The schema object for the object
* @param fActiveRecord $object The instance of the class to check
* @param array &$values An associative array of all values going into the row (needs all for multi-field unique constraint checking)
* @param array &$old_values The old values for the record
* @return array A single element associative array with the key being the primary keys joined by ,s and the value being the error message
*/
static private function checkPrimaryKeys($schema, $object, &$values, &$old_values)
{
$class = get_class($object);
$table = fORM::tablize($class);
$db = fORMDatabase::retrieve($class, 'read');
$pk_columns = $schema->getKeys($table, 'primary');
$columns = array();
$found_value = FALSE;
foreach ($pk_columns as $pk_column) {
$columns[] = fORM::getColumnName($class, $pk_column);
if ($values[$pk_column]) {
$found_value = TRUE;
}
}
if (!$found_value) {
return;
}
$different = FALSE;
foreach ($pk_columns as $pk_column) {
if (!fActiveRecord::hasOld($old_values, $pk_column)) {
continue;
}
$old_value = fActiveRecord::retrieveOld($old_values, $pk_column);
$value = $values[$pk_column];
if (self::isCaseInsensitive($class, $pk_column) && self::stringlike($value) && self::stringlike($old_value)) {
if (fUTF8::lower($value) != fUTF8::lower($old_value)) {
$different = TRUE;
}
} elseif ($old_value != $value) {
$different = TRUE;
}
}
if (!$different) {
return;
}
try {
$params = array(
"SELECT %r FROM %r WHERE ",
$pk_columns,
$table
);
$column_info = $schema->getColumnInfo($table);
$conditions = array();
foreach ($pk_columns as $pk_column) {
$value = $values[$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'];
}
if (self::isCaseInsensitive($class, $pk_column) && self::stringlike($value)) {
$condition = fORMDatabase::makeCondition($schema, $table, $pk_column, '=', $value);
$conditions[] = str_replace('%r', 'LOWER(%r)', $condition);
$params[] = $pk_column;
$params[] = fUTF8::lower($value);
} else {
$conditions[] = fORMDatabase::makeCondition($schema, $table, $pk_column, '=', $value);
$params[] = $pk_column;
$params[] = $value;
}
}
$params[0] .= join(' AND ', $conditions);
$result = call_user_func_array($db->translatedQuery, $params);
$result->tossIfNoRows();
return array(join(',', $pk_columns) => self::compose(
'Another %1$s with the same %2$s already exists',
fORM::getRecordName($class),
fGrammar::joinArray($columns, 'and')
));
} catch (fNoRowsException $e) { }
}
/**
* Validates against a regex rule
*
* @param string $class The class the column is part of
* @param array &$values An associative array of all values for the record
* @param string $column The column to check
* @param string $regex The PCRE regular expression
* @param string $message The message to use if the value does not match the regular expression
* @return string An error message for the rule
*/
static private function checkRegexRule($class, &$values, $column, $regex, $message)
{
if ($values[$column] === NULL) {
return;
}
if (preg_match($regex, $values[$column])) {
return;
}
return self::compose(
'%s' . str_replace('%', '%%', $message),
fValidationException::formatField(fORM::getColumnName($class, $column))
);
}
/**
* Validates against a *-to-many one or more rule
*
* @param fActiveRecord $object The object being checked
* @param array &$values The values for the object
* @param array &$related_records The related records for the object
* @param string $related_class The name of the related class
* @param string $route The name of the route from the class to the related class
* @return string An error message for the rule
*/
static private function checkRelatedOneOrMoreRule($object, &$values, &$related_records, $related_class, $route)
{
$related_table = fORM::tablize($related_class);
$class = get_class($object);
$exists = $object->exists();
$records_are_set = isset($related_records[$related_table][$route]);
$has_records = $records_are_set && $related_records[$related_table][$route]['count'];
if ($exists && (!$records_are_set || $has_records)) {
return;
}
if (!$exists && $has_records) {
return;
}
return self::compose(
'%sPlease select at least one',
fValidationException::formatField(fGrammar::pluralize(fORMRelated::getRelatedRecordName($class, $related_class, $route)))
);
}
/**
* Validates values against unique constraints
*
* @param fSchema $schema The schema object for the object
* @param fActiveRecord $object The instance of the class to check
* @param array &$values The values to check
* @param array &$old_values The old values for the record
* @return array An aray of error messages for the unique constraints
*/
static private function checkUniqueConstraints($schema, $object, &$values, &$old_values)
{
$class = get_class($object);
$table = fORM::tablize($class);
$db = fORMDatabase::retrieve($class, 'read');
$key_info = $schema->getKeys($table);
$pk_columns = $key_info['primary'];
$unique_keys = $key_info['unique'];
$messages = array();
foreach ($unique_keys AS $unique_columns) {
settype($unique_columns, 'array');
// NULL values are unique
$found_not_null = FALSE;
foreach ($unique_columns as $unique_column) {
if ($values[$unique_column] !== NULL) {
$found_not_null = TRUE;
}
}
if (!$found_not_null) {
continue;
}
$params = array(
"SELECT %r FROM %r WHERE ",
$key_info['primary'],
$table
);
$column_info = $schema->getColumnInfo($table);
$conditions = array();
foreach ($unique_columns as $unique_column) {
$value = $values[$unique_column];
// This makes sure the query performs the way an insert will
if ($value === NULL && $column_info[$unique_column]['not_null'] && $column_info[$unique_column]['default'] !== NULL) {
$value = $column_info[$unique_column]['default'];
}
if (self::isCaseInsensitive($class, $unique_column) && self::stringlike($value)) {
$condition = fORMDatabase::makeCondition($schema, $table, $unique_column, '=', $value);
$conditions[] = str_replace('%r', 'LOWER(%r)', $condition);
$params[] = $table . '.' . $unique_column;
$params[] = fUTF8::lower($value);
} else {
$conditions[] = fORMDatabase::makeCondition($schema, $table, $unique_column, '=', $value);
$params[] = $table . '.' . $unique_column;
$params[] = $value;
}
}
$params[0] .= join(' AND ', $conditions);
if ($object->exists()) {
foreach ($pk_columns as $pk_column) {
$value = fActiveRecord::retrieveOld($old_values, $pk_column, $values[$pk_column]);
$params[0] .= ' AND ' . fORMDatabase::makeCondition($schema, $table, $pk_column, '<>', $value);
$params[] = $table . '.' . $pk_column;
$params[] = $value;
}
}
try {
$result = call_user_func_array($db->translatedQuery, $params);
$result->tossIfNoRows();
// If an exception was not throw, we have existing values
$column_names = array();
foreach ($unique_columns as $unique_column) {
$column_names[] = fORM::getColumnName($class, $unique_column);
}
if (sizeof($column_names) == 1) {
$messages[join('', $unique_columns)] = self::compose(
'%sThe value specified must be unique, however it already exists',
fValidationException::formatField(join('', $column_names))
);
} else {
$messages[join(',', $unique_columns)] = self::compose(
'%sThe values specified must be a unique combination, however the specified combination already exists',
fValidationException::formatField(join(', ', $column_names))
);
}
} catch (fNoRowsException $e) { }
}
return $messages;
}
/**
* Validates against a valid values rule
*
* @param string $class The class this rule applies to
* @param array &$values An associative array of all values for the record
* @param string $column The column the rule applies to
* @param array $valid_values An array of valid values to check the column against
* @return string The error message for the rule specified
*/
static private function checkValidValuesRule($class, &$values, $column, $valid_values)
{
if ($values[$column] === NULL) {
return;
}
if (!in_array($values[$column], $valid_values)) {
return self::compose(
'%1$sPlease choose from one of the following: %2$s',
fValidationException::formatField(fORM::getColumnName($class, $column)),