RequiredIf.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace Illuminate\Validation\Rules;
  3. use Closure;
  4. use InvalidArgumentException;
  5. use Stringable;
  6. class RequiredIf implements Stringable
  7. {
  8. /**
  9. * The condition that validates the attribute.
  10. *
  11. * @var (\Closure(): bool)|bool
  12. */
  13. public $condition;
  14. /**
  15. * Create a new required validation rule based on a condition.
  16. *
  17. * @param (\Closure(): bool)|bool|null $condition
  18. *
  19. * @throws \InvalidArgumentException
  20. */
  21. public function __construct($condition)
  22. {
  23. if (is_null($condition)) {
  24. $condition = false;
  25. }
  26. if ($condition instanceof Closure || is_bool($condition)) {
  27. $this->condition = $condition;
  28. } else {
  29. throw new InvalidArgumentException('The provided condition must be a callable or boolean.');
  30. }
  31. }
  32. /**
  33. * Convert the rule to a validation string.
  34. *
  35. * @return string
  36. */
  37. public function __toString()
  38. {
  39. if (is_callable($this->condition)) {
  40. return call_user_func($this->condition) ? 'required' : '';
  41. }
  42. return $this->condition ? 'required' : '';
  43. }
  44. }