1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Imanghafoori\HeyMan; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\Gate; |
6
|
|
|
|
7
|
|
|
class YouShouldHave |
8
|
|
|
{ |
9
|
|
|
public $predicate; |
10
|
|
|
|
11
|
43 |
|
public function youShouldHaveRole($role) |
12
|
|
|
{ |
13
|
43 |
|
return $this->thisGateShouldAllow('heyman.youShouldHaveRole', $role); |
14
|
|
|
} |
15
|
|
|
|
16
|
47 |
|
public function thisGateShouldAllow($gate, ...$args) |
17
|
|
|
{ |
18
|
47 |
|
$gate = $this->defineNewGate($gate); |
19
|
|
|
|
20
|
|
|
$this->predicate = function () use ($gate, $args) { |
21
|
43 |
|
return Gate::allows($gate, $args); |
22
|
|
|
}; |
23
|
|
|
|
24
|
47 |
|
return new Otherwise(); |
25
|
|
|
} |
26
|
|
|
|
27
|
3 |
|
public function thisClosureShouldAllow($callback, array $parameters = []) |
28
|
|
|
{ |
29
|
3 |
|
return $this->thisMethodShouldAllow($callback, $parameters); |
30
|
|
|
} |
31
|
|
|
|
32
|
5 |
|
public function thisMethodShouldAllow($callback, array $parameters = []) |
33
|
|
|
{ |
34
|
|
|
$this->predicate = function () use ($callback, $parameters) { |
35
|
5 |
|
return (boolean) app()->call($callback, $parameters); |
36
|
|
|
}; |
37
|
|
|
|
38
|
5 |
|
return new Otherwise(); |
39
|
|
|
} |
40
|
|
|
|
41
|
3 |
|
public function thisValueShouldAllow($value) |
42
|
|
|
{ |
43
|
|
|
$this->predicate = function () use ($value) { |
44
|
3 |
|
return (boolean) $value; |
45
|
|
|
}; |
46
|
3 |
|
return new Otherwise(); |
47
|
|
|
} |
48
|
|
|
|
49
|
6 |
|
public function youShouldBeGuest() |
50
|
|
|
{ |
51
|
|
|
$this->predicate = function () { |
52
|
6 |
|
return auth()->guest(); |
53
|
|
|
}; |
54
|
|
|
|
55
|
6 |
|
return new Otherwise(); |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
public function youShouldBeLoggedIn() |
59
|
|
|
{ |
60
|
|
|
$this->predicate = function () { |
61
|
1 |
|
return auth()->check(); |
62
|
|
|
}; |
63
|
|
|
|
64
|
1 |
|
return new Otherwise(); |
65
|
|
|
} |
66
|
|
|
|
67
|
3 |
|
public function immediately() |
68
|
|
|
{ |
69
|
|
|
$this->predicate = function () { |
70
|
3 |
|
return false; |
71
|
|
|
}; |
72
|
|
|
|
73
|
3 |
|
return new Responder(); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @param $gate |
78
|
|
|
* @return string |
79
|
|
|
*/ |
80
|
47 |
|
private function defineNewGate($gate): string |
81
|
|
|
{ |
82
|
|
|
// Define a Gate for inline closures passed as gate |
83
|
47 |
|
if (is_callable($gate)) { |
84
|
1 |
|
$closure = $gate; |
85
|
1 |
|
$gate = str_random(10); |
86
|
1 |
|
Gate::define($gate, $closure); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
// Define a Gate for "class@method" gates |
90
|
47 |
|
if (is_string($gate) && str_contains($gate, '@')) { |
91
|
1 |
|
Gate::define($gate, $gate); |
92
|
|
|
} |
93
|
|
|
|
94
|
47 |
|
return $gate; |
95
|
|
|
} |
96
|
|
|
} |