Conditionable.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Illuminate\Support\Traits;
  3. use Closure;
  4. use Illuminate\Support\HigherOrderWhenProxy;
  5. trait Conditionable
  6. {
  7. /**
  8. * Apply the callback if the given "value" is (or resolves to) truthy.
  9. *
  10. * @template TWhenParameter
  11. * @template TWhenReturnType
  12. *
  13. * @param (\Closure($this): TWhenParameter)|TWhenParameter|null $value
  14. * @param (callable($this, TWhenParameter): TWhenReturnType)|null $callback
  15. * @param (callable($this, TWhenParameter): TWhenReturnType)|null $default
  16. * @return $this|TWhenReturnType
  17. */
  18. public function when($value = null, ?callable $callback = null, ?callable $default = null)
  19. {
  20. $value = $value instanceof Closure ? $value($this) : $value;
  21. if (func_num_args() === 0) {
  22. return new HigherOrderWhenProxy($this);
  23. }
  24. if (func_num_args() === 1) {
  25. return (new HigherOrderWhenProxy($this))->condition($value);
  26. }
  27. if ($value) {
  28. return $callback($this, $value) ?? $this;
  29. } elseif ($default) {
  30. return $default($this, $value) ?? $this;
  31. }
  32. return $this;
  33. }
  34. /**
  35. * Apply the callback if the given "value" is (or resolves to) falsy.
  36. *
  37. * @template TUnlessParameter
  38. * @template TUnlessReturnType
  39. *
  40. * @param (\Closure($this): TUnlessParameter)|TUnlessParameter|null $value
  41. * @param (callable($this, TUnlessParameter): TUnlessReturnType)|null $callback
  42. * @param (callable($this, TUnlessParameter): TUnlessReturnType)|null $default
  43. * @return $this|TUnlessReturnType
  44. */
  45. public function unless($value = null, ?callable $callback = null, ?callable $default = null)
  46. {
  47. $value = $value instanceof Closure ? $value($this) : $value;
  48. if (func_num_args() === 0) {
  49. return (new HigherOrderWhenProxy($this))->negateConditionOnCapture();
  50. }
  51. if (func_num_args() === 1) {
  52. return (new HigherOrderWhenProxy($this))->condition(! $value);
  53. }
  54. if (! $value) {
  55. return $callback($this, $value) ?? $this;
  56. } elseif ($default) {
  57. return $default($this, $value) ?? $this;
  58. }
  59. return $this;
  60. }
  61. }