ClosureValidationRule.php 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Illuminate\Validation;
  3. use Illuminate\Contracts\Validation\Rule as RuleContract;
  4. class ClosureValidationRule implements RuleContract
  5. {
  6. /**
  7. * The callback that validates the attribute.
  8. *
  9. * @var \Closure
  10. */
  11. public $callback;
  12. /**
  13. * Indicates if the validation callback failed.
  14. *
  15. * @var bool
  16. */
  17. public $failed = false;
  18. /**
  19. * The validation error message.
  20. *
  21. * @var string|null
  22. */
  23. public $message;
  24. /**
  25. * Create a new Closure based validation rule.
  26. *
  27. * @param \Closure $callback
  28. * @return void
  29. */
  30. public function __construct($callback)
  31. {
  32. $this->callback = $callback;
  33. }
  34. /**
  35. * Determine if the validation rule passes.
  36. *
  37. * @param string $attribute
  38. * @param mixed $value
  39. * @return bool
  40. */
  41. public function passes($attribute, $value)
  42. {
  43. $this->failed = false;
  44. $this->callback->__invoke($attribute, $value, function ($message) {
  45. $this->failed = true;
  46. $this->message = $message;
  47. });
  48. return ! $this->failed;
  49. }
  50. /**
  51. * Get the validation error message.
  52. *
  53. * @return string
  54. */
  55. public function message()
  56. {
  57. return $this->message;
  58. }
  59. }