rule.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. * Create a new validation Rule instance.
  18. *
  19. * @param array $attributes
  20. * @return void
  21. */
  22. public function __construct($attributes)
  23. {
  24. $this->attributes = $attributes;
  25. }
  26. /**
  27. * Run the validation rule.
  28. *
  29. * @param array $attributes
  30. * @param Error_Collector $errors
  31. * @return void
  32. */
  33. public function validate($attributes, $errors)
  34. {
  35. foreach ($this->attributes as $attribute)
  36. {
  37. if ( ! $this->check($attribute, $attributes))
  38. {
  39. $errors->add($attribute, $this->prepare_message($attribute));
  40. }
  41. }
  42. }
  43. /**
  44. * Prepare the message to be added to the error collector.
  45. *
  46. * @param string $attribute
  47. * @return string
  48. */
  49. private function prepare_message($attribute)
  50. {
  51. if (is_null($this->message))
  52. {
  53. throw new \Exception("An error message must be specified for every Eloquent validation rule.");
  54. }
  55. $message = $this->message;
  56. // ---------------------------------------------------------
  57. // Replace any place-holders with their actual values.
  58. //
  59. // Attribute place-holders are loaded from the language
  60. // directory. If the line doesn't exist, the attribute
  61. // name will be used instead.
  62. // ---------------------------------------------------------
  63. if (strpos($message, ':attribute'))
  64. {
  65. $message = str_replace(':attribute', Lang::line('attributes.'.$attribute)->get($attribute), $message);
  66. }
  67. if ($this instanceof Rules\Size_Of)
  68. {
  69. $message = str_replace(':max', $this->maximum, $message);
  70. $message = str_replace(':min', $this->minimum, $message);
  71. $message = str_replace(':size', $this->length, $message);
  72. }
  73. return $message;
  74. }
  75. /**
  76. * Set the validation error message.
  77. *
  78. * @param string $message
  79. * @return Rule
  80. */
  81. public function message($message)
  82. {
  83. $this->message = $message;
  84. return $this;
  85. }
  86. }