Completed
Push — master ( 6af785...cbc83f )
by Iman
05:36
created

Gate   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 12
dl 0
loc 36
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A youShouldHaveRole() 0 3 1
A thisGateShouldAllow() 0 6 1
A defineNewGate() 0 15 4
1
<?php
2
3
namespace Imanghafoori\HeyMan\Conditions;
4
5
use Illuminate\Support\Facades\Gate as GateFacade;
6
7
trait Gate
8
{
9
    public function thisGateShouldAllow($gate, ...$parameters)
10
    {
11
        $gate = $this->defineNewGate($gate);
12
13
        return function (...$payload) use ($gate, $parameters) {
14
            return GateFacade::allows($gate, (array_merge($parameters, ...$payload)));
15
        };
16
    }
17
18
    /**
19
     * @param $gate
20
     *
21
     * @return string
22
     */
23
    private function defineNewGate($gate): string
24
    {
25
        // Define a Gate for inline closures passed as gate
26
        if (is_callable($gate)) {
27
            $closure = $gate;
28
            $gate = str_random(10);
29
            GateFacade::define($gate, $closure);
30
        }
31
32
        // Define a Gate for "class@method" gates
33
        if (is_string($gate) && str_contains($gate, '@')) {
34
            GateFacade::define($gate, $gate);
35
        }
36
37
        return $gate;
38
    }
39
40
    public function youShouldHaveRole(string $role)
41
    {
42
        return $this->thisGateShouldAllow('heyman.youShouldHaveRole', $role);
43
    }
44
45
46
}