Conditionable.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Conditionable;
  12. use Closure;
  13. trait Conditionable
  14. {
  15. /**
  16. * Apply the callback if the given "value" is (or resolves to) truthy.
  17. *
  18. * @template TWhenParameter
  19. * @template TWhenReturnType
  20. *
  21. * @param null|(Closure($this): TWhenParameter)|TWhenParameter $value
  22. * @param null|(callable($this, TWhenParameter): TWhenReturnType) $callback
  23. * @param null|(callable($this, TWhenParameter): TWhenReturnType) $default
  24. * @param null|mixed $value
  25. * @return $this|TWhenReturnType
  26. */
  27. public function when($value = null, ?callable $callback = null, ?callable $default = null)
  28. {
  29. $value = $value instanceof Closure ? $value($this) : $value;
  30. if (func_num_args() === 0) {
  31. return new HigherOrderWhenProxy($this);
  32. }
  33. if (func_num_args() === 1) {
  34. return (new HigherOrderWhenProxy($this))->condition($value);
  35. }
  36. if ($value) {
  37. return $callback($this, $value) ?? $this;
  38. }
  39. if ($default) {
  40. return $default($this, $value) ?? $this;
  41. }
  42. return $this;
  43. }
  44. /**
  45. * Apply the callback if the given "value" is (or resolves to) falsy.
  46. *
  47. * @template TUnlessParameter
  48. * @template TUnlessReturnType
  49. *
  50. * @param null|(Closure($this): TUnlessParameter)|TUnlessParameter $value
  51. * @param null|(callable($this, TUnlessParameter): TUnlessReturnType) $callback
  52. * @param null|(callable($this, TUnlessParameter): TUnlessReturnType) $default
  53. * @param null|mixed $value
  54. * @return $this|TUnlessReturnType
  55. */
  56. public function unless($value = null, ?callable $callback = null, ?callable $default = null)
  57. {
  58. $value = $value instanceof Closure ? $value($this) : $value;
  59. if (func_num_args() === 0) {
  60. return (new HigherOrderWhenProxy($this))->negateConditionOnCapture();
  61. }
  62. if (func_num_args() === 1) {
  63. return (new HigherOrderWhenProxy($this))->condition(! $value);
  64. }
  65. if (! $value) {
  66. return $callback($this, $value) ?? $this;
  67. }
  68. if ($default) {
  69. return $default($this, $value) ?? $this;
  70. }
  71. return $this;
  72. }
  73. }