rule.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php namespace System\Validation;
  2. use System\Lang;
  3. abstract class Rule {
  4. /**
  5. * The attributes being validated by the rule.
  6. *
  7. * @var array
  8. */
  9. public $attributes;
  10. /**
  11. * The validation error message.
  12. *
  13. * @var string
  14. */
  15. public $message;
  16. /**
  17. * The error type. This is used for rules that have more than
  18. * one type of error such as Size_Of and Upload_Of.
  19. *
  20. * @var string
  21. */
  22. public $error;
  23. /**
  24. * Create a new validation Rule instance.
  25. *
  26. * @param array $attributes
  27. * @return void
  28. */
  29. public function __construct($attributes)
  30. {
  31. $this->attributes = $attributes;
  32. }
  33. /**
  34. * Run the validation rule.
  35. *
  36. * @param array $attributes
  37. * @param array $errors
  38. * @return void
  39. */
  40. public function validate($attributes, &$errors)
  41. {
  42. foreach ($this->attributes as $attribute)
  43. {
  44. $this->error = null;
  45. if ( ! $this->check($attribute, $attributes))
  46. {
  47. $message = Message::get($this, $attribute);
  48. // -------------------------------------------------------------
  49. // Make sure the error message is not duplicated.
  50. //
  51. // For example, the Nullable rules can add a "required" message.
  52. // If the same message has already been added we don't want to
  53. // add it again.
  54. // -------------------------------------------------------------
  55. if ( ! array_key_exists($attribute, $errors) or ! is_array($errors[$attribute]) or ! in_array($message, $errors[$attribute]))
  56. {
  57. $errors[$attribute][] = $message;
  58. }
  59. }
  60. }
  61. }
  62. /**
  63. * Set the validation error message.
  64. *
  65. * @param string $message
  66. * @return Rule
  67. */
  68. public function message($message)
  69. {
  70. $this->message = $message;
  71. return $this;
  72. }
  73. }