rule.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. protected $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. if ( ! $this->check($attribute, $attributes))
  45. {
  46. $errors[$attribute][] = $this->prepare_message($attribute);
  47. }
  48. }
  49. }
  50. /**
  51. * Prepare the message to be added to the error collector.
  52. *
  53. * @param string $attribute
  54. * @return string
  55. */
  56. private function prepare_message($attribute)
  57. {
  58. if (is_null($this->message))
  59. {
  60. throw new \Exception("An error message must be specified for every validation rule.");
  61. }
  62. $message = $this->message;
  63. // ---------------------------------------------------------
  64. // Replace any place-holders with their actual values.
  65. //
  66. // Attribute place-holders are loaded from the language
  67. // directory. If the line doesn't exist, the attribute
  68. // name will be used instead.
  69. // ---------------------------------------------------------
  70. if (strpos($message, ':attribute'))
  71. {
  72. $message = str_replace(':attribute', Lang::line('attributes.'.$attribute)->get($attribute), $message);
  73. }
  74. if ($this instanceof Rules\Size_Of)
  75. {
  76. $message = str_replace(':max', $this->maximum, $message);
  77. $message = str_replace(':min', $this->minimum, $message);
  78. $message = str_replace(':size', $this->length, $message);
  79. }
  80. return $message;
  81. }
  82. /**
  83. * Set the validation error message.
  84. *
  85. * @param string $message
  86. * @return Rule
  87. */
  88. public function message($message)
  89. {
  90. $this->message = $message;
  91. return $this;
  92. }
  93. }