Completed
Push — master ( de6709...9195ef )
by Freek
05:38 queued 03:36
created

PermissionRegistrar::getPermissions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 9.4285
1
<?php
2
3
namespace Spatie\Permission;
4
5
use Log;
6
use Exception;
7
use Illuminate\Contracts\Auth\Access\Gate;
8
use Illuminate\Contracts\Cache\Repository;
9
use Spatie\Permission\Contracts\Permission;
10
11
class PermissionRegistrar
12
{
13
    /**
14
     * @var Gate
15
     */
16
    protected $gate;
17
18
    /**
19
     * @var Repository
20
     */
21
    protected $cache;
22
23
    /**
24
     * @var string
25
     */
26
    protected $cacheKey = 'spatie.permission.cache';
27
28
    /**
29
     * @param Gate $gate
30
     * @param Repository $cache
31
     */
32
    public function __construct(Gate $gate, Repository $cache)
33
    {
34
        $this->gate = $gate;
35
        $this->cache = $cache;
36
    }
37
38
    /**
39
     *  Register the permissions.
40
     *
41
     * @return bool
42
     */
43
    public function registerPermissions()
44
    {
45
        try {
46
            $this->getPermissions()->map(function ($permission) {
47
                $this->gate->define($permission->name, function ($user) use ($permission) {
48
                    return $user->hasPermissionTo($permission);
49
                });
50
            });
51
52
            return true;
53
        } catch (Exception $exception) {
54
            if ($this->shouldLogException()) {
55
                Log::alert(
56
                    "Could not register permissions because {$exception->getMessage()}".PHP_EOL
57
                    .$exception->getTraceAsString());
58
            }
59
60
            return false;
61
        }
62
    }
63
64
    /**
65
     *  Forget the cached permissions.
66
     */
67
    public function forgetCachedPermissions()
68
    {
69
        $this->cache->forget($this->cacheKey);
70
    }
71
72
    /**
73
     * Get the current permissions.
74
     *
75
     * @return \Illuminate\Database\Eloquent\Collection
76
     */
77
    protected function getPermissions()
78
    {
79
        return $this->cache->rememberForever($this->cacheKey, function () {
80
            return app(Permission::class)->with('roles')->get();
81
        });
82
    }
83
84
    /**
85
     * @return bool
86
     */
87
    protected function shouldLogException()
88
    {
89
        $logSetting = config('laravel-permission.log_registration_exception');
90
91
        if (is_null($logSetting))  {
92
            return true;
93
        }
94
        
95
        return $logSetting;
96
    }
97
}
98