Completed
Push — master ( 78b3ab...6795be )
by wen
15:30
created

PermissionsConfig::isEditable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
4
namespace Sco\Admin\Config;
5
6
use JsonSerializable;
7
use Illuminate\Contracts\Support\Arrayable;
8
use Illuminate\Contracts\Support\Jsonable;
9
use Sco\Attributes\HasAttributesTrait;
10
11
class PermissionsConfig implements Arrayable, Jsonable, JsonSerializable
12
{
13
    use HasAttributesTrait;
14
15
    protected $default = [
16
        'view'   => true,
17
        'create' => true,
18
        'edit'   => true,
19
        'delete' => true,
20
    ];
21
22
    public function __construct($config)
23
    {
24
        $this->compile($config);
25
    }
26
27
    protected function compile($config)
28
    {
29
        if (is_array($config)) {
30
            $config = array_merge($this->default, $config);
31
            foreach ($config as $key => $item) {
32
                $val = $item instanceof \Closure ? $item() : $item;
33
                $this->setAttribute($key, $val ? true : false);
34
            }
35
        } else {
36
            $val = $config instanceof \Closure ? $config() : $config;
37
            foreach ($this->default as $key => $item) {
38
                $this->setAttribute($key, $val ? true : false);
39
            }
40
        }
41
    }
42
43
    public function isCreatable()
44
    {
45
        return $this->can('create');
46
    }
47
48
    public function isViewable()
49
    {
50
        return $this->can('view');
51
    }
52
53
    public function isEditable()
54
    {
55
        return $this->can('edit');
56
    }
57
58
    public function isDeletable()
59
    {
60
        return $this->can('delete');
61
    }
62
63
    public function can($permission)
64
    {
65
        if (!is_array($permission)) {
66
            $permission = [$permission];
67
        }
68
69
        foreach ($permission as $item) {
70
            $hasPerm = $this->getAttribute($item, false);
71
            if (!$hasPerm) {
72
                return false;
73
            }
74
        }
75
        return true;
76
    }
77
}
78