-
Notifications
You must be signed in to change notification settings - Fork 440
/
Copy pathValidations.php
911 lines (806 loc) · 24 KB
/
Validations.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
<?php
/**
* These two classes have been <i>heavily borrowed</i> from Ruby on Rails' ActiveRecord so much that
* this piece can be considered a straight port. The reason for this is that the vaildation process is
* tricky due to order of operations/events. The former combined with PHP's odd typecasting means
* that it was easier to formulate this piece base on the rails code.
*
* @package ActiveRecord
*/
namespace ActiveRecord;
use ActiveRecord\Model;
use IteratorAggregate;
use ArrayIterator;
/**
* Manages validations for a {@link Model}.
*
* This class isn't meant to be directly used. Instead you define
* validators thru static variables in your {@link Model}. Example:
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_length_of = array(
* array('name', 'within' => array(30,100),
* array('state', 'is' => 2)
* );
* }
*
* $person = new Person();
* $person->name = 'Tito';
* $person->state = 'this is not two characters';
*
* if (!$person->is_valid())
* print_r($person->errors);
* </code>
*
* @package ActiveRecord
* @see Errors
* @link http://www.phpactiverecord.org/guides/validations
*/
class Validations
{
private $model;
private $options = array();
private $validators = array();
private $record;
private static $VALIDATION_FUNCTIONS = array(
'validates_presence_of',
'validates_size_of',
'validates_length_of',
'validates_inclusion_of',
'validates_exclusion_of',
'validates_format_of',
'validates_numericality_of',
'validates_uniqueness_of'
);
private static $DEFAULT_VALIDATION_OPTIONS = array(
'on' => 'save',
'allow_null' => false,
'allow_blank' => false,
'message' => null,
);
private static $ALL_RANGE_OPTIONS = array(
'is' => null,
'within' => null,
'in' => null,
'minimum' => null,
'maximum' => null,
);
private static $ALL_NUMERICALITY_CHECKS = array(
'greater_than' => null,
'greater_than_or_equal_to' => null,
'equal_to' => null,
'less_than' => null,
'less_than_or_equal_to' => null,
'odd' => null,
'even' => null
);
/**
* Constructs a {@link Validations} object.
*
* @param Model $model The model to validate
* @return Validations
*/
public function __construct(Model $model)
{
$this->model = $model;
$this->record = new Errors($this->model);
$this->klass = Reflections::instance()->get(get_class($this->model));
$this->validators = array_intersect(array_keys($this->klass->getStaticProperties()), self::$VALIDATION_FUNCTIONS);
}
public function get_record()
{
return $this->record;
}
/**
* Returns validator data.
*
* @return array
*/
public function rules()
{
$data = array();
foreach ($this->validators as $validate)
{
$attrs = $this->klass->getStaticPropertyValue($validate);
foreach (wrap_strings_in_arrays($attrs) as $attr)
{
$field = $attr[0];
if (!isset($data[$field]) || !is_array($data[$field]))
$data[$field] = array();
$attr['validator'] = $validate;
unset($attr[0]);
array_push($data[$field],$attr);
}
}
return $data;
}
/**
* Runs the validators.
*
* @return Errors the validation errors if any
*/
public function validate()
{
foreach ($this->validators as $validate)
{
$definition = $this->klass->getStaticPropertyValue($validate);
$this->$validate(wrap_strings_in_arrays($definition));
}
$model_reflection = Reflections::instance()->get($this->model);
if ($model_reflection->hasMethod('validate') && $model_reflection->getMethod('validate')->isPublic())
$this->model->validate();
$this->record->clear_model();
return $this->record;
}
/**
* Validates a field is not null and not blank.
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_presence_of = array(
* array('first_name'),
* array('last_name')
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>message:</b> custom error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_presence_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES['blank'], 'on' => 'save'));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$this->record->add_on_blank($options[0], $options['message']);
}
}
/**
* Validates that a value is included the specified array.
*
* <code>
* class Car extends ActiveRecord\Model {
* static $validates_inclusion_of = array(
* array('fuel_type', 'in' => array('hyrdogen', 'petroleum', 'electric')),
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>in/within:</b> attribute should/shouldn't be a value within an array</li>
* <li><b>message:</b> custome error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_inclusion_of($attrs)
{
$this->validates_inclusion_or_exclusion_of('inclusion', $attrs);
}
/**
* This is the opposite of {@link validates_include_of}.
*
* Available options:
*
* <ul>
* <li><b>in/within:</b> attribute should/shouldn't be a value within an array</li>
* <li><b>message:</b> custome error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
* @see validates_inclusion_of
*/
public function validates_exclusion_of($attrs)
{
$this->validates_inclusion_or_exclusion_of('exclusion', $attrs);
}
/**
* Validates that a value is in or out of a specified list of values.
*
* Available options:
*
* <ul>
* <li><b>in/within:</b> attribute should/shouldn't be a value within an array</li>
* <li><b>message:</b> custome error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @see validates_inclusion_of
* @see validates_exclusion_of
* @param string $type Either inclusion or exclusion
* @param $attrs Validation definition
*/
public function validates_inclusion_or_exclusion_of($type, $attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES[$type], 'on' => 'save'));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$attribute = $options[0];
$var = $this->model->$attribute;
if (isset($options['in']))
$enum = $options['in'];
elseif (isset($options['within']))
$enum = $options['within'];
if (!is_array($enum))
array($enum);
$message = str_replace('%s', $var, $options['message']);
if ($this->is_null_with_option($var, $options) || $this->is_blank_with_option($var, $options))
continue;
if (('inclusion' == $type && !in_array($var, $enum)) || ('exclusion' == $type && in_array($var, $enum)))
$this->record->add($attribute, $message);
}
}
/**
* Validates that a value is numeric.
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_numericality_of = array(
* array('salary', 'greater_than' => 19.99, 'less_than' => 99.99)
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>only_integer:</b> value must be an integer (e.g. not a float)</li>
* <li><b>even:</b> must be even</li>
* <li><b>odd:</b> must be odd"</li>
* <li><b>greater_than:</b> must be greater than specified number</li>
* <li><b>greater_than_or_equal_to:</b> must be greater than or equal to specified number</li>
* <li><b>equal_to:</b> ...</li>
* <li><b>less_than:</b> ...</li>
* <li><b>less_than_or_equal_to:</b> ...</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_numericality_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('only_integer' => false));
// Notice that for fixnum and float columns empty strings are converted to nil.
// Validates whether the value of the specified attribute is numeric by trying to convert it to a float with Kernel.Float
// (if only_integer is false) or applying it to the regular expression /\A[+\-]?\d+\Z/ (if only_integer is set to true).
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$attribute = $options[0];
$var = $this->model->$attribute;
$numericalityOptions = array_intersect_key(self::$ALL_NUMERICALITY_CHECKS, $options);
if ($this->is_null_with_option($var, $options))
continue;
$not_a_number_message = (isset($options['message']) ? $options['message'] : Errors::$DEFAULT_ERROR_MESSAGES['not_a_number']);
if (true === $options['only_integer'] && !is_integer($var))
{
if (!preg_match('/\A[+-]?\d+\Z/', (string)($var)))
{
$this->record->add($attribute, $not_a_number_message);
continue;
}
}
else
{
if (!is_numeric($var))
{
$this->record->add($attribute, $not_a_number_message);
continue;
}
$var = (float)$var;
}
foreach ($numericalityOptions as $option => $check)
{
$option_value = $options[$option];
$message = (isset($options['message']) ? $options['message'] : Errors::$DEFAULT_ERROR_MESSAGES[$option]);
if ('odd' != $option && 'even' != $option)
{
$option_value = (float)$options[$option];
if (!is_numeric($option_value))
throw new ValidationsArgumentError("$option must be a number");
$message = str_replace('%d', $option_value, $message);
if ('greater_than' == $option && !($var > $option_value))
$this->record->add($attribute, $message);
elseif ('greater_than_or_equal_to' == $option && !($var >= $option_value))
$this->record->add($attribute, $message);
elseif ('equal_to' == $option && !($var == $option_value))
$this->record->add($attribute, $message);
elseif ('less_than' == $option && !($var < $option_value))
$this->record->add($attribute, $message);
elseif ('less_than_or_equal_to' == $option && !($var <= $option_value))
$this->record->add($attribute, $message);
}
else
{
if (('odd' == $option && !Utils::is_odd($var)) || ('even' == $option && Utils::is_odd($var)))
$this->record->add($attribute, $message);
}
}
}
}
/**
* Alias of {@link validates_length_of}
*
* @param array $attrs Validation definition
*/
public function validates_size_of($attrs)
{
$this->validates_length_of($attrs);
}
/**
* Validates that a value is matches a regex.
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_format_of = array(
* array('email', 'with' => '/^.*?@.*$/')
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>with:</b> a regular expression</li>
* <li><b>message:</b> custom error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_format_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES['invalid'], 'on' => 'save', 'with' => null));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$attribute = $options[0];
$var = $this->model->$attribute;
if (is_null($options['with']) || !is_string($options['with']))
throw new ValidationsArgumentError('A regular expression must be supplied as the [with] option of the configuration array.');
else
$expression = $options['with'];
if ($this->is_null_with_option($var, $options) || $this->is_blank_with_option($var, $options))
continue;
if (!@preg_match($expression, $var))
$this->record->add($attribute, $options['message']);
}
}
/**
* Validates the length of a value.
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_length_of = array(
* array('name', 'within' => array(1,50))
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>is:</b> attribute should be exactly n characters long</li>
* <li><b>in/within:</b> attribute should be within an range array(min,max)</li>
* <li><b>maximum/minimum:</b> attribute should not be above/below respectively</li>
* <li><b>message:</b> custome error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings. (Even if this is set to false, a null string is always shorter than a maximum value.)</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_length_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array(
'too_long' => Errors::$DEFAULT_ERROR_MESSAGES['too_long'],
'too_short' => Errors::$DEFAULT_ERROR_MESSAGES['too_short'],
'wrong_length' => Errors::$DEFAULT_ERROR_MESSAGES['wrong_length']
));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$range_options = array_intersect(array_keys(self::$ALL_RANGE_OPTIONS), array_keys($attr));
sort($range_options);
switch (sizeof($range_options))
{
case 0:
throw new ValidationsArgumentError('Range unspecified. Specify the [within], [maximum], or [is] option.');
case 1:
break;
default:
throw new ValidationsArgumentError('Too many range options specified. Choose only one.');
}
$attribute = $options[0];
$var = $this->model->$attribute;
if ($this->is_null_with_option($var, $options) || $this->is_blank_with_option($var, $options))
continue;
if ($range_options[0] == 'within' || $range_options[0] == 'in')
{
$range = $options[$range_options[0]];
if (!(Utils::is_a('range', $range)))
throw new ValidationsArgumentError("$range_options[0] must be an array composing a range of numbers with key [0] being less than key [1]");
$range_options = array('minimum', 'maximum');
$attr['minimum'] = $range[0];
$attr['maximum'] = $range[1];
}
foreach ($range_options as $range_option)
{
$option = $attr[$range_option];
if ((int)$option <= 0)
throw new ValidationsArgumentError("$range_option value cannot use a signed integer.");
if (is_float($option))
throw new ValidationsArgumentError("$range_option value cannot use a float for length.");
if (!($range_option == 'maximum' && is_null($this->model->$attribute)))
{
$messageOptions = array('is' => 'wrong_length', 'minimum' => 'too_short', 'maximum' => 'too_long');
if (isset($options['message']))
$message = $options['message'];
else
$message = $options[$messageOptions[$range_option]];
$message = str_replace('%d', $option, $message);
$attribute_value = $this->model->$attribute;
$len = strlen($attribute_value);
$value = (int)$attr[$range_option];
if ('maximum' == $range_option && $len > $value)
$this->record->add($attribute, $message);
if ('minimum' == $range_option && $len < $value)
$this->record->add($attribute, $message);
if ('is' == $range_option && $len !== $value)
$this->record->add($attribute, $message);
}
}
}
}
/**
* Validates the uniqueness of a value.
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_uniqueness_of = array(
* array('name'),
* array(array('blah','bleh'), 'message' => 'blech')
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>with:</b> a regular expression</li>
* <li><b>message:</b> custom error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_uniqueness_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array(
'message' => Errors::$DEFAULT_ERROR_MESSAGES['unique']
));
// Retrieve connection from model for quote_name method
$connection = $this->klass->getMethod('connection')->invoke(null);
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$pk = $this->model->get_primary_key();
$pk_value = $this->model->{$pk[0]};
if (is_array($options[0]))
{
$add_record = join("_and_", $options[0]);
$fields = $options[0];
}
else
{
$add_record = $options[0];
$fields = array($options[0]);
}
$sql = "";
$conditions = array("");
$pk_quoted = $connection->quote_name($pk[0]);
if ($pk_value === null)
$sql = "{$pk_quoted} IS NOT NULL";
else
{
$sql = "{$pk_quoted} != ?";
array_push($conditions,$pk_value);
}
foreach ($fields as $field)
{
$field = $this->model->get_real_attribute_name($field);
$quoted_field = $connection->quote_name($field);
$sql .= " AND {$quoted_field}=?";
array_push($conditions,$this->model->$field);
}
$conditions[0] = $sql;
if ($this->model->exists(array('conditions' => $conditions)))
$this->record->add($add_record, $options['message']);
}
}
private function is_null_with_option($var, &$options)
{
return (is_null($var) && (isset($options['allow_null']) && $options['allow_null']));
}
private function is_blank_with_option($var, &$options)
{
return (Utils::is_blank($var) && (isset($options['allow_blank']) && $options['allow_blank']));
}
}
/**
* Class that holds {@link Validations} errors.
*
* @package ActiveRecord
*/
class Errors implements IteratorAggregate
{
private $model;
private $errors;
public static $DEFAULT_ERROR_MESSAGES = array(
'inclusion' => "is not included in the list",
'exclusion' => "is reserved",
'invalid' => "is invalid",
'confirmation' => "doesn't match confirmation",
'accepted' => "must be accepted",
'empty' => "can't be empty",
'blank' => "can't be blank",
'too_long' => "is too long (maximum is %d characters)",
'too_short' => "is too short (minimum is %d characters)",
'wrong_length' => "is the wrong length (should be %d characters)",
'taken' => "has already been taken",
'not_a_number' => "is not a number",
'greater_than' => "must be greater than %d",
'equal_to' => "must be equal to %d",
'less_than' => "must be less than %d",
'odd' => "must be odd",
'even' => "must be even",
'unique' => "must be unique",
'less_than_or_equal_to' => "must be less than or equal to %d",
'greater_than_or_equal_to' => "must be greater than or equal to %d"
);
/**
* Constructs an {@link Errors} object.
*
* @param Model $model The model the error is for
* @return Errors
*/
public function __construct(Model $model)
{
$this->model = $model;
}
/**
* Nulls $model so we don't get pesky circular references. $model is only needed during the
* validation process and so can be safely cleared once that is done.
*/
public function clear_model()
{
$this->model = null;
}
/**
* Add an error message.
*
* @param string $attribute Name of an attribute on the model
* @param string $msg The error message
*/
public function add($attribute, $msg)
{
if (is_null($msg))
$msg = self :: $DEFAULT_ERROR_MESSAGES['invalid'];
if (!isset($this->errors[$attribute]))
$this->errors[$attribute] = array($msg);
else
$this->errors[$attribute][] = $msg;
}
/**
* Adds an error message only if the attribute value is {@link http://www.php.net/empty empty}.
*
* @param string $attribute Name of an attribute on the model
* @param string $msg The error message
*/
public function add_on_empty($attribute, $msg)
{
if (empty($msg))
$msg = self::$DEFAULT_ERROR_MESSAGES['empty'];
if (empty($this->model->$attribute))
$this->add($attribute, $msg);
}
/**
* Retrieve error messages for an attribute.
*
* @param string $attribute Name of an attribute on the model
* @return array or null if there is no error.
*/
public function __get($attribute)
{
if (!isset($this->errors[$attribute]))
return null;
return $this->errors[$attribute];
}
/**
* Adds the error message only if the attribute value was null or an empty string.
*
* @param string $attribute Name of an attribute on the model
* @param string $msg The error message
*/
public function add_on_blank($attribute, $msg)
{
if (!$msg)
$msg = self::$DEFAULT_ERROR_MESSAGES['blank'];
if (($value = $this->model->$attribute) === '' || $value === null)
$this->add($attribute, $msg);
}
/**
* Returns true if the specified attribute had any error messages.
*
* @param string $attribute Name of an attribute on the model
* @return boolean
*/
public function is_invalid($attribute)
{
return isset($this->errors[$attribute]);
}
/**
* Returns the error message(s) for the specified attribute or null if none.
*
* @param string $attribute Name of an attribute on the model
* @return string/array Array of strings if several error occured on this attribute.
*/
public function on($attribute)
{
$errors = $this->$attribute;
return $errors && count($errors) == 1 ? $errors[0] : $errors;
}
/**
* Returns the internal errors object.
*
* <code>
* $model->errors->get_raw_errors();
*
* # array(
* # "name" => array("can't be blank"),
* # "state" => array("is the wrong length (should be 2 chars)",
* # )
* </code>
*/
public function get_raw_errors()
{
return $this->errors;
}
/**
* Returns all the error messages as an array.
*
* <code>
* $model->errors->full_messages();
*
* # array(
* # "Name can't be blank",
* # "State is the wrong length (should be 2 chars)"
* # )
* </code>
*
* @return array
*/
public function full_messages()
{
$full_messages = array();
$this->to_array(function($attribute, $message) use (&$full_messages) {
$full_messages[] = $message;
});
return $full_messages;
}
/**
* Returns all the error messages as an array, including error key.
*
* <code>
* $model->errors->errors();
*
* # array(
* # "name" => array("Name can't be blank"),
* # "state" => array("State is the wrong length (should be 2 chars)")
* # )
* </code>
*
* @param callable $closure Closure to fetch the errors in some other format (optional)
* This closure has the signature function($attribute, $message)
* and is called for each available error message.
* @return array
*/
public function to_array($closure=null)
{
$errors = array();
if ($this->errors)
{
foreach ($this->errors as $attribute => $messages)
{
foreach ($messages as $msg)
{
if (is_null($msg))
continue;
$errors[$attribute][] = ($message = Utils::human_attribute($attribute) . ' ' . $msg);
if ($closure)
$closure($attribute,$message);
}
}
}
return $errors;
}
/**
* Convert all error messages to a String.
* This function is called implicitely if the object is casted to a string:
*
* <code>
* echo $error;
*
* # "Name can't be blank\nState is the wrong length (should be 2 chars)"
* </code>
* @return string
*/
public function __toString()
{
return implode("\n", $this->full_messages());
}
/**
* Returns true if there are no error messages.
* @return boolean
*/
public function is_empty()
{
return empty($this->errors);
}
/**
* Clears out all error messages.
*/
public function clear()
{
$this->errors = array();
}
/**
* Returns the number of error messages there are.
* @return int
*/
public function size()
{
if ($this->is_empty())
return 0;
$count = 0;
foreach ($this->errors as $attribute => $error)
$count += count($error);
return $count;
}
/**
* Returns an iterator to the error messages.
*
* This will allow you to iterate over the {@link Errors} object using foreach.
*
* <code>
* foreach ($model->errors as $msg)
* echo "$msg\n";
* </code>
*
* @return ArrayIterator
*/
public function getIterator()
{
return new ArrayIterator($this->full_messages());
}
}