1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Imanghafoori\Helpers; |
4
|
|
|
|
5
|
|
|
use Illuminate\Http\Exceptions\HttpResponseException; |
6
|
|
|
use Symfony\Component\HttpFoundation\Response; |
7
|
|
|
|
8
|
|
|
class Nullable |
9
|
|
|
{ |
10
|
|
|
private $result; |
11
|
|
|
|
12
|
|
|
private $predicate = null; |
13
|
|
|
|
14
|
|
|
private $message = ''; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Nullable constructor. |
18
|
|
|
* |
19
|
|
|
* @param mixed $value |
20
|
|
|
* @param array $message |
21
|
|
|
* @param callable $predicate |
22
|
|
|
*/ |
23
|
10 |
|
public function __construct($value, array $message = [], $predicate = null) |
24
|
|
|
{ |
25
|
10 |
|
$this->result = $value; |
26
|
10 |
|
$this->message = $message; |
|
|
|
|
27
|
10 |
|
$this->predicate = $predicate; |
28
|
10 |
|
} |
29
|
|
|
|
30
|
1 |
|
public function getOr($default) |
31
|
|
|
{ |
32
|
1 |
|
$p = $this->getPredicate(); |
33
|
|
|
|
34
|
1 |
|
if (!$p($this->result)) { |
35
|
1 |
|
return $this->result; |
36
|
|
|
} |
37
|
|
|
|
38
|
1 |
|
if (is_callable($default)) { |
39
|
|
|
return call_user_func($default); |
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
return $default; |
43
|
|
|
} |
44
|
|
|
|
45
|
2 |
|
public function getOrAbort($code, $message = '', array $headers = []) |
46
|
|
|
{ |
47
|
2 |
|
if (!is_null($this->result)) { |
48
|
1 |
|
return $this->result; |
49
|
|
|
} |
50
|
|
|
|
51
|
1 |
|
abort($code, $message, $headers); |
52
|
|
|
} |
53
|
|
|
|
54
|
6 |
|
public function getOrSend($callable) |
55
|
|
|
{ |
56
|
6 |
|
if (!is_null($this->result)) { |
57
|
1 |
|
return $this->result; |
58
|
|
|
} |
59
|
|
|
|
60
|
5 |
|
if (is_callable($callable)) { |
61
|
3 |
|
$callable = call_user_func_array($callable, $this->message); |
62
|
|
|
} |
63
|
|
|
|
64
|
5 |
|
if (is_a($callable, Response::class)) { |
65
|
3 |
|
$response = $callable; |
66
|
|
|
} |
67
|
|
|
|
68
|
5 |
|
if (isset($response)) { |
69
|
3 |
|
throw new HttpResponseException($response); |
70
|
|
|
} |
71
|
|
|
|
72
|
2 |
|
throw new \InvalidArgumentException('You must provide a valid http response or a callable.'); |
73
|
|
|
} |
74
|
|
|
|
75
|
2 |
|
public function getOrThrow($exception, ...$parameters) |
76
|
|
|
{ |
77
|
|
|
|
78
|
2 |
|
if (!is_null($this->result)) { |
79
|
|
|
return $this->result; |
80
|
|
|
} |
81
|
|
|
|
82
|
2 |
|
throw_if(true, $exception, ...$parameters); |
83
|
|
|
} |
84
|
|
|
|
85
|
1 |
|
private function getPredicate() |
86
|
|
|
{ |
87
|
1 |
|
if (is_callable($this->predicate)) { |
88
|
1 |
|
$p = $this->predicate; |
89
|
|
|
} else { |
90
|
|
|
$p = function ($r) { |
91
|
1 |
|
return is_null($r); |
92
|
1 |
|
}; |
93
|
|
|
} |
94
|
|
|
|
95
|
1 |
|
return $p; |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|
Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..