-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathRole.php
120 lines (105 loc) · 2.58 KB
/
Role.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
namespace Pingpong\Trusty;
use Illuminate\Database\Eloquent\Model;
use Pingpong\Trusty\Traits\SlugableTrait;
class Role extends Model
{
use SlugableTrait;
/**
* Fillable property.
*
* @var array
*/
protected $fillable = ['name', 'slug', 'description'];
/**
* Relation to "Permission".
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function permissions()
{
return $this->belongsToMany(config('trusty.model.permission'))->withTimestamps();
}
/**
* Query scope for searching permission.
*
* @param $query
* @param $search
*
* @return mixed
*/
public function scopeSearch($query, $search)
{
return $query->whereName($search)
->orWhere('id', intval($search))
->orWhere('slug', intval($search));
}
/**
* Attach permission to role.
*
* @param mixed $id
*/
public function addPermission($id)
{
$this->permissions()->attach($id);
}
/**
* Detach permission from role.
*
* @param mixed $ids
*/
public function removePermission($ids)
{
$ids = is_array($ids) ? $ids : func_get_args();
$this->permissions()->detach($ids);
}
/**
* Remove all permissions from role.
*/
public function clearPermissions()
{
$this->removePermission($this->permissions->lists('id'));
}
/**
* Relation to "User".
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany(config('trusty.model.user'))->withTimestamps();
}
/**
* Determine wether the current role has permission that given by name parameter.
*
* @param string $name
*
* @return bool
*/
public function can($name)
{
foreach ($this->permissions as $permission) {
if ($permission->name == $name || $permission->id == $name) {
return true;
}
}
return false;
}
/**
* Handle dynamic method.
*
* @param string $method
* @param array $parameters
*
* @return bool
*/
public function __call($method, $parameters = array())
{
if (starts_with($method, 'can') and $method != 'can') {
return $this->can(snake_case(substr($method, 3)));
} else {
$query = $this->newQuery();
return call_user_func_array(array($query, $method), $parameters);
}
}
}