Conditionable.php 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace Illuminate\Support\Traits;
  3. trait Conditionable
  4. {
  5. /**
  6. * Apply the callback if the given "value" is truthy.
  7. *
  8. * @param mixed $value
  9. * @param callable $callback
  10. * @param callable|null $default
  11. * @return $this|mixed
  12. */
  13. public function when($value, $callback, $default = null)
  14. {
  15. if ($value) {
  16. return $callback($this, $value) ?: $this;
  17. } elseif ($default) {
  18. return $default($this, $value) ?: $this;
  19. }
  20. return $this;
  21. }
  22. /**
  23. * Apply the callback if the given "value" is falsy.
  24. *
  25. * @param mixed $value
  26. * @param callable $callback
  27. * @param callable|null $default
  28. * @return $this|mixed
  29. */
  30. public function unless($value, $callback, $default = null)
  31. {
  32. if (! $value) {
  33. return $callback($this, $value) ?: $this;
  34. } elseif ($default) {
  35. return $default($this, $value) ?: $this;
  36. }
  37. return $this;
  38. }
  39. }