rule.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php namespace System\Validation;
  2. use System\Lang;
  3. abstract class Rule {
  4. /**
  5. * The attributes being validated.
  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. * @param Validator $class
  21. * @return void
  22. */
  23. public function __construct($attributes)
  24. {
  25. $this->attributes = $attributes;
  26. }
  27. /**
  28. * Run the validation rule.
  29. *
  30. * @param array $attributes
  31. * @param Error_Collector $errors
  32. * @return void
  33. */
  34. public function validate($attributes, $errors)
  35. {
  36. if (is_null($this->message))
  37. {
  38. throw new \Exception("An error message must be specified for every Eloquent validation rule.");
  39. }
  40. foreach ($this->attributes as $attribute)
  41. {
  42. if ( ! $this->check($attribute, $attributes))
  43. {
  44. $errors->add($attribute, $this->prepare_message($attribute));
  45. }
  46. }
  47. }
  48. /**
  49. * Prepare the message to be added to the error collector.
  50. *
  51. * Attribute and size place-holders will replace with their actual values.
  52. *
  53. * @param string $attribute
  54. * @return string
  55. */
  56. private function prepare_message($attribute)
  57. {
  58. $message = $this->message;
  59. if (strpos($message, ':attribute'))
  60. {
  61. $message = str_replace(':attribute', Lang::line('attributes.'.$attribute)->get(), $message);
  62. }
  63. if ($this instanceof Rules\Size_Of)
  64. {
  65. $message = str_replace(':max', $this->maximum, $message);
  66. $message = str_replace(':min', $this->minimum, $message);
  67. $message = str_replace(':size', $this->length, $message);
  68. }
  69. return $message;
  70. }
  71. /**
  72. * Set the validation error message.
  73. *
  74. * @param string $message
  75. * @return Rule
  76. */
  77. public function message($message)
  78. {
  79. $this->message = $message;
  80. return $this;
  81. }
  82. }