1 | <?php |
||
2 | |||
3 | namespace Terranet\Administrator\Actions; |
||
4 | |||
5 | use Illuminate\Contracts\Auth\Authenticatable as User; |
||
6 | use Illuminate\Database\Eloquent\Model; |
||
7 | use Illuminate\Support\Collection as BaseCollection; |
||
8 | |||
9 | class Collection extends BaseCollection |
||
10 | { |
||
11 | 4 | public function __construct($items = []) |
|
12 | { |
||
13 | // initialize action classes only at first execution. |
||
14 | 4 | if (\is_array($items)) { |
|
15 | $items = array_map(function ($handler) { |
||
16 | 4 | return new $handler(); |
|
17 | 4 | }, $items); |
|
18 | } |
||
19 | |||
20 | 4 | parent::__construct($items); |
|
21 | 4 | } |
|
22 | |||
23 | /** |
||
24 | * Find action by name. |
||
25 | * |
||
26 | * @param $name |
||
27 | * |
||
28 | * @return mixed |
||
29 | */ |
||
30 | 1 | public function find($name) |
|
31 | { |
||
32 | return $this->first(function ($action) use ($name) { |
||
33 | 1 | return class_basename($action) === studly_case($name); |
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
34 | 1 | }); |
|
35 | } |
||
36 | |||
37 | /** |
||
38 | * Leave actions which User $user is authorized to execute. |
||
39 | * |
||
40 | * @param null|User $user |
||
41 | * @param null|Model $model |
||
42 | * |
||
43 | * @return static |
||
44 | */ |
||
45 | 2 | public function authorized(?User $user = null, Model $model = null) |
|
46 | { |
||
47 | 2 | $user = $user ?: auth('admin')->user(); |
|
48 | 2 | $model = $model ?: app('scaffold.module')->model(); |
|
49 | |||
50 | return $this->filter(function ($action) use ($user, $model) { |
||
51 | // authorize action only if action allows it. |
||
52 | 2 | if (method_exists($action, 'authorize')) { |
|
53 | 1 | return $action->authorize($user, $model); |
|
54 | } |
||
55 | |||
56 | 1 | return true; |
|
57 | 2 | }); |
|
58 | } |
||
59 | } |
||
60 |