Completed
Push — master ( 27aaeb...0eb7b3 )
by wen
03:21
created

Permission::getMenuTreeList()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Sco\Admin\Models;
4
5
use DB;
6
use Cache;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Http\Request;
9
use Sco\Admin\Exceptions\AdminHttpException;
10
use Sco\Admin\Traits\EntrustPermissionTrait;
11
use Sco\Tree\Traits\TreeTrait;
12
13
/**
14
 * Sco\Admin\Models\Permission
15
 *
16
 * @property int $id 主键
17
 * @property int $pid 父ID
18
 * @property string $icon 图标class
19
 * @property string $display_name 显示名称
20
 * @property string $name 名称
21
 * @property bool $is_menu 是否作为菜单
22
 * @property bool $sort 排序
23
 * @property string $description 描述
24
 * @property \Carbon\Carbon $created_at
25
 * @property \Carbon\Carbon $updated_at
26
 * @property-read \Illuminate\Database\Eloquent\Collection|\Sco\Admin\Models\Role[] $roles
27
 * @method static \Illuminate\Database\Query\Builder|\Sco\Admin\Models\Permission whereCreatedAt($value)
28
 * @method static \Illuminate\Database\Query\Builder|\Sco\Admin\Models\Permission whereDescription($value)
29
 * @method static \Illuminate\Database\Query\Builder|\Sco\Admin\Models\Permission whereDisplayName($value)
30
 * @method static \Illuminate\Database\Query\Builder|\Sco\Admin\Models\Permission whereIcon($value)
31
 * @method static \Illuminate\Database\Query\Builder|\Sco\Admin\Models\Permission whereId($value)
32
 * @method static \Illuminate\Database\Query\Builder|\Sco\Admin\Models\Permission whereIsMenu($value)
33
 * @method static \Illuminate\Database\Query\Builder|\Sco\Admin\Models\Permission whereName($value)
34
 * @method static \Illuminate\Database\Query\Builder|\Sco\Admin\Models\Permission wherePid($value)
35
 * @method static \Illuminate\Database\Query\Builder|\Sco\Admin\Models\Permission whereSort($value)
36
 * @method static \Illuminate\Database\Query\Builder|\Sco\Admin\Models\Permission whereUpdatedAt($value)
37
 * @mixin \Eloquent
38
 */
39
class Permission extends Model
40
{
41
    use TreeTrait, EntrustPermissionTrait;
42
43
    protected $hidden = ['created_at', 'updated_at'];
44
45
    protected $guarded = ['created_at', 'updated_at'];
46
47
    protected $treeNodeParentIdName = 'pid';
48
49
    private $allRoutes = null;
50
51
    private $validList = null;
0 ignored issues
show
Unused Code introduced by
The property $validList is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
52
53
    private $permList = null;
54
55
    private $menuList = null;
56
57
    protected $events = [
58
        'created'  => \Sco\ActionLog\Events\ModelWasCreated::class,
59
        'updated'  => \Sco\ActionLog\Events\ModelWasUpdated::class,
60
        'deleted'  => \Sco\ActionLog\Events\ModelWasDeleted::class,
61
    ];
62
63
64
    public function __construct(array $attributes = [])
65
    {
66
        parent::__construct($attributes);
67
        $this->table = config('admin.permissions_table');
68
    }
69
70
71
    /**
72
     * @return \Illuminate\Support\Collection
73
     */
74
    public function getMenuTreeList()
75
    {
76
        $routes = $this->getDescendants(0);
77
        //dd($routes);
78
        return $routes;
79
    }
80
81
    private function getAll()
82
    {
83
        if ($this->allRoutes) {
84
            return $this->allRoutes;
85
        }
86
87
        $this->allRoutes = Cache::rememberForever('permission_all',
88
            function () {
89
                return $this->orderBy('sort')->get();
0 ignored issues
show
Documentation Bug introduced by
The method orderBy does not exist on object<Sco\Admin\Models\Permission>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
90
            });
91
        return $this->allRoutes;
92
    }
93
94
    /**
95
     * Tree Trait 获取所有节点
96
     *
97
     * @return mixed|null
98
     */
99
    protected function getTreeAllNodes()
100
    {
101
        return $this->getAll();
102
    }
103
104
    /**
105
     * 获取有效的路由列表
106
     *
107
     * @return \Illuminate\Support\Collection
108
     */
109
    /*public function getValidRouteList()
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
110
    {
111
        if ($this->validList) {
112
            return $this->validList;
113
        }
114
115
        $all = $this->getAll();
116
117
        $this->validList = collect([]);
118
        foreach ($all as $route) {
119
            if (!empty($route->uri) && $route->uri != '#') {
120
                $this->validList->push($route);
121
            }
122
        }
123
        return $this->validList;
124
    }*/
125
126
    /**
127
     * 获取权限列表
128
     *
129
     * @return \Illuminate\Support\Collection|null
130
     */
131
    public function getPermRouteList()
132
    {
133
        if ($this->permList) {
134
            return $this->permList;
135
        }
136
137
        return $this->permList = $this->getLayerOfDescendants(0);
138
    }
139
140
    public function getMenuList()
141
    {
142
        if ($this->menuList) {
143
            return $this->menuList;
144
        }
145
        $all = $this->getAll();
146
147
        $routes = collect([]);
148
        foreach ($all as $route) {
149
            if ($route->is_menu) {
150
                $routes->push($route);
151
            }
152
        }
153
154
        $this->setAllNodes($routes);
155
        return $this->menuList = $this->getLayerOfDescendants(0);
156
    }
157
158
    /*public function getInfoById($id)
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
159
    {
160
        return $this->getSelf($id);
161
    }
162
163
    public function getInfoByName($name)
164
    {
165
        $all = $this->getAll();
166
        $key = $all->search(function ($item) use ($name) {
167
            return $item->name == $name;
168
        });
169
        return $key === false ? false : $all->get($key);
170
    }*/
171
172
    /*public function getParentTree($id)
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
173
    {
174
        return $this->getAncestors($id);
175
    }
176
177
    public function getParentTreeAndSelfById($id)
178
    {
179
        $self = $this->getInfoById($id);
180
        if ($self) {
181
            $parent = $this->getParentTree($self->id);
182
            $parent->push($self);
183
            return $parent;
184
        }
185
        return false;
186
    }
187
188
    public function getParentTreeAndSelfByName($name)
189
    {
190
        $self = $this->getInfoByName($name);
191
        if ($self) {
192
            $parent = $this->getParentTree($self->id);
193
            $parent->push($self);
194
            return $parent;
195
        }
196
        return false;
197
    }*/
198
199
    public function saveMenu(Request $request)
200
    {
201
        if (empty($request->input('id'))) {
202
            $model = $this;
203
        } else {
204
            $model = $this->findOrFail($request->input('id'));
0 ignored issues
show
Documentation Bug introduced by
The method findOrFail does not exist on object<Sco\Admin\Models\Permission>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
205
        }
206
207
        $model->pid          = $request->input('pid');
208
        $model->display_name = $request->input('display_name');
209
        $model->name         = $request->input('name');
210
        $model->icon         = $request->input('icon') ?: '';
211
        $model->is_menu      = $request->input('is_menu', 0);
212
        $model->sort         = $request->input('sort', 255);
213
        $model->description  = $request->input('description') ?: '';
214
215
        $model->save();
216
217
        $this->clearCache();
218
        return true;
219
    }
220
221
    /**
222
     * 删除菜单
223
     *
224
     * @param int|array $ids 菜单ID
225
     *
226
     * @return bool
227
     */
228
    public function deleteMenu($ids)
229
    {
230
        if (!is_array($ids)) {
231
            $ids = [intval($ids)];
232
        }
233
        $items = collect();
234
        foreach ($ids as $id) {
235
            $items->push($id);
236
            $items = $items->merge($this->getDescendants($id)->keys());
237
        }
238
        $items = $items->unique();
239
        if ($items->isEmpty()) {
240
            throw new AdminHttpException('菜单不存在');
241
        }
242
243
        DB::transaction(function () use ($items) {
244
            $this->destroy($items->toArray());
245
        });
246
247
        $this->clearCache();
248
249
        return true;
250
    }
251
252
    private function clearCache()
253
    {
254
        Cache::forget('permission_all');
255
    }
256
}
257