AnyOf.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace Illuminate\Validation\Rules;
  3. use Illuminate\Contracts\Validation\Rule;
  4. use Illuminate\Contracts\Validation\ValidatorAwareRule;
  5. use Illuminate\Support\Arr;
  6. use Illuminate\Support\Facades\Validator;
  7. use InvalidArgumentException;
  8. class AnyOf implements Rule, ValidatorAwareRule
  9. {
  10. /**
  11. * The rules to match against.
  12. *
  13. * @var array
  14. */
  15. protected array $rules = [];
  16. /**
  17. * The validator performing the validation.
  18. *
  19. * @var \Illuminate\Validation\Validator
  20. */
  21. protected $validator;
  22. /**
  23. * Sets the validation rules to match against.
  24. *
  25. * @param array $rules
  26. *
  27. * @throws \InvalidArgumentException
  28. */
  29. public function __construct($rules)
  30. {
  31. if (! is_array($rules)) {
  32. throw new InvalidArgumentException('The provided value must be an array of validation rules.');
  33. }
  34. $this->rules = $rules;
  35. }
  36. /**
  37. * Determine if the validation rule passes.
  38. *
  39. * @param string $attribute
  40. * @param mixed $value
  41. * @return bool
  42. */
  43. public function passes($attribute, $value)
  44. {
  45. foreach ($this->rules as $rule) {
  46. $validator = Validator::make(
  47. Arr::isAssoc(Arr::wrap($value)) ? $value : [$value],
  48. Arr::isAssoc(Arr::wrap($rule)) ? $rule : [$rule],
  49. $this->validator->customMessages,
  50. $this->validator->customAttributes
  51. );
  52. if ($validator->passes()) {
  53. return true;
  54. }
  55. }
  56. return false;
  57. }
  58. /**
  59. * Get the validation error messages.
  60. *
  61. * @return array
  62. */
  63. public function message()
  64. {
  65. $message = $this->validator->getTranslator()->get('validation.any_of');
  66. return $message === 'validation.any_of'
  67. ? ['The :attribute field is invalid.']
  68. : $message;
  69. }
  70. /**
  71. * Set the current validator.
  72. *
  73. * @param \Illuminate\Contracts\Validation\Validator $validator
  74. * @return $this
  75. */
  76. public function setValidator($validator)
  77. {
  78. $this->validator = $validator;
  79. return $this;
  80. }
  81. }