ClosureValidationRule.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace Illuminate\Validation;
  3. use Illuminate\Contracts\Validation\Rule as RuleContract;
  4. use Illuminate\Contracts\Validation\ValidatorAwareRule;
  5. use Illuminate\Translation\CreatesPotentiallyTranslatedStrings;
  6. class ClosureValidationRule implements RuleContract, ValidatorAwareRule
  7. {
  8. use CreatesPotentiallyTranslatedStrings;
  9. /**
  10. * The callback that validates the attribute.
  11. *
  12. * @var \Closure
  13. */
  14. public $callback;
  15. /**
  16. * Indicates if the validation callback failed.
  17. *
  18. * @var bool
  19. */
  20. public $failed = false;
  21. /**
  22. * The validation error messages.
  23. *
  24. * @var array
  25. */
  26. public $messages = [];
  27. /**
  28. * The current validator.
  29. *
  30. * @var \Illuminate\Validation\Validator
  31. */
  32. protected $validator;
  33. /**
  34. * Create a new Closure based validation rule.
  35. *
  36. * @param \Closure $callback
  37. */
  38. public function __construct($callback)
  39. {
  40. $this->callback = $callback;
  41. }
  42. /**
  43. * Determine if the validation rule passes.
  44. *
  45. * @param string $attribute
  46. * @param mixed $value
  47. * @return bool
  48. */
  49. public function passes($attribute, $value)
  50. {
  51. $this->failed = false;
  52. $this->callback->__invoke($attribute, $value, function ($attribute, $message = null) {
  53. $this->failed = true;
  54. return $this->pendingPotentiallyTranslatedString($attribute, $message);
  55. }, $this->validator);
  56. return ! $this->failed;
  57. }
  58. /**
  59. * Get the validation error messages.
  60. *
  61. * @return array
  62. */
  63. public function message()
  64. {
  65. return $this->messages;
  66. }
  67. /**
  68. * Set the current validator.
  69. *
  70. * @param \Illuminate\Validation\Validator $validator
  71. * @return $this
  72. */
  73. public function setValidator($validator)
  74. {
  75. $this->validator = $validator;
  76. return $this;
  77. }
  78. }