nullable_rule.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php namespace System\Validation;
  2. use System\Str;
  3. abstract class Nullable_Rule extends Rule {
  4. /**
  5. * Indicates an empty value should be considered valid.
  6. *
  7. * @var bool
  8. */
  9. public $allow_empty = false;
  10. /**
  11. * Indicates null should be considered valid.
  12. *
  13. * @var bool
  14. */
  15. public $allow_null = false;
  16. /**
  17. * Evaluate the validity of an attribute.
  18. *
  19. * If this method returns a value, the child class will return it
  20. * as the result of the validation. Otherwise, the child class will
  21. * continue validating as normal.
  22. *
  23. * @param string $attribute
  24. * @param array $attributes
  25. * @return mixed
  26. */
  27. public function check($attribute, $attributes)
  28. {
  29. // -------------------------------------------------------------
  30. // If the attribute doesn't exist, the child's validation
  31. // check will be be halted, and a presence_of error will be
  32. // raised if null is not allowed.
  33. // -------------------------------------------------------------
  34. if ( ! array_key_exists($attribute, $attributes))
  35. {
  36. if ( ! $this->allow_null)
  37. {
  38. $this->error = 'presence_of';
  39. }
  40. return is_null($this->error);
  41. }
  42. // -------------------------------------------------------------
  43. // Make sure the attribute is not an empty string. An error
  44. // will be raised if the attribute is empty and empty strings
  45. // are not allowed, halting the child's validation.
  46. // -------------------------------------------------------------
  47. elseif (Str::length((string) $attributes[$attribute]) == 0 and ! $this->allow_empty)
  48. {
  49. $this->error = 'presence_of';
  50. return false;
  51. }
  52. }
  53. /**
  54. * Allow a empty and null to be considered valid.
  55. *
  56. * @return Nullable_Rule
  57. */
  58. public function not_required()
  59. {
  60. return $this->allow_empty()->allow_null();
  61. }
  62. /**
  63. * Allow empty to be considered valid.
  64. *
  65. * @return Nullable_Rule
  66. */
  67. public function allow_empty()
  68. {
  69. $this->allow_empty = true;
  70. return $this;
  71. }
  72. /**
  73. * Allow null to be considered valid.
  74. *
  75. * @return Nullable_Rule
  76. */
  77. public function allow_null()
  78. {
  79. $this->allow_null = true;
  80. return $this;
  81. }
  82. }