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