Passed
Push — master ( b9fea2...a6a214 )
by Iman
03:14
created

YouShouldHave::thisMethodShouldAllow()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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