length_of.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php namespace System\Validation\Rules;
  2. use System\Str;
  3. use System\Validation\Rangable_Rule;
  4. class Length_Of extends Rangable_Rule {
  5. /**
  6. * Evaluate the validity of an attribute.
  7. *
  8. * @param string $attribute
  9. * @param array $attributes
  10. * @return bool
  11. */
  12. public function check($attribute, $attributes)
  13. {
  14. if ( ! is_null($nullable = parent::check($attribute, $attributes)))
  15. {
  16. return $nullable;
  17. }
  18. $value = trim((string) $attributes[$attribute]);
  19. // ---------------------------------------------------------
  20. // Validate the exact length of the attribute.
  21. // ---------------------------------------------------------
  22. if ( ! is_null($this->size) and Str::length($value) !== $this->size)
  23. {
  24. $this->error = 'string_wrong_size';
  25. }
  26. // ---------------------------------------------------------
  27. // Validate the maximum length of the attribute.
  28. // ---------------------------------------------------------
  29. elseif ( ! is_null($this->maximum) and Str::length($value) > $this->maximum)
  30. {
  31. $this->error = 'string_too_big';
  32. }
  33. // ---------------------------------------------------------
  34. // Validate the minimum length of the attribute.
  35. // ---------------------------------------------------------
  36. elseif ( ! is_null($this->minimum) and Str::length($value) < $this->minimum)
  37. {
  38. $this->error = 'string_too_small';
  39. }
  40. return is_null($this->error);
  41. }
  42. }