UserTrait::hasRole()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
rs 9.2
cc 4
eloc 6
nc 6
nop 1
1
<?php
2
/**
3
 * CakePHP permission handling library
4
 * @author Tao <[email protected]>
5
 */
6
namespace Slince\CakePermission\Model\Entity;
7
8
use Cake\Cache\Cache;
9
use Cake\Collection\Collection;
10
use Cake\ORM\Query;
11
use Slince\CakePermission\Constants;
12
use Slince\CakePermission\Model\Table\RolesTableTrait;
13
use Slince\CakePermission\TableFactory;
14
15
trait UserTrait
16
{
17
    use HasPermissionTrait;
18
19
    /**
20
     * Alias of "hasAnyPermission"
21
     * @param $permission
22
     * @return boolean
23
     */
24
    public function can($permission)
25
    {
26
        return $this->hasAnyPermission((array)$permission);
27
    }
28
29
    /**
30
     * Assigns a role or an array of roles for the user
31
     * @param string|Role|array $role
32
     * @return boolean
33
     */
34
    public function assignRole($role)
35
    {
36
        $roles = is_array($role) ? $role : [$role];
37
        $roles = array_map(function($role){
38
            return is_string($role) ? Role::find($role) : $role;
39
        }, $roles);
40
        $this->set('roles', $roles);
0 ignored issues
show
Bug introduced by
It seems like set() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
41
        $result = TableFactory::getUserModel()->save($this) !== false;
42
        RolesTableTrait::refreshCache($this->id);
0 ignored issues
show
Bug introduced by
The property id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
43
        return $result;
44
    }
45
46
    /**
47
     * Revokes the specified role from the user
48
     * @param string|Role $role
49
     * @return boolean
50
     */
51
    public function removeRole($role)
52
    {
53
        $role = is_string($role) ? Role::find($role) : $role;
54
        $result = TableFactory::getUserModel()->association('Roles')->unlink($this, [$role]);
55
        RolesTableTrait::refreshCache($this->id);
56
        return $result;
57
    }
58
59
    /**
60
     * Removes all roles
61
     */
62
    public function removeAllRoles()
63
    {
64
        $result = TableFactory::getUserModel()->association('Roles')->unlink($this, $this->getAllRoles() );
65
        RolesTableTrait::refreshCache($this->id);
66
        return $result;
67
    }
68
69
    /**
70
     * Checks whether the user has thr role
71
     * @param string|Role $role
72
     * @return bool
73
     */
74
    public function hasRole($role)
75
    {
76
        $roleName = is_string($role) ? $role : $role->get('name');
77
        foreach ($this->getAllRoles() as $role) {
78
            if ($role->get('name') == $roleName) {
79
                return true;
80
            }
81
        }
82
        return false;
83
    }
84
85
    /**
86
     * Gets all the permissions for the user
87
     * @return Role[]
88
     */
89
    public function getAllPermissions()
90
    {
91
        $roles = $this->getAllRoles();
92
        $permissions = $roles ? call_user_func_array('array_merge', array_map(function(Role $role){
93
            return $role->getAllPermissions();
94
        }, $roles)) : [];
95
        return (new Collection($permissions))->combine('slug', function($permission){
96
            return $permission;
97
        })->toArray();
98
    }
99
100
    /**
101
     * Gets all roles of the user
102
     * @return Role[]
103
     */
104
    public function getAllRoles()
105
    {
106
        $id = $this->get(TableFactory::getUserModel()->getPrimaryKey());
0 ignored issues
show
Bug introduced by
It seems like get() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
107
        return Cache::remember(sprintf(Constants::CACHE_ROLES, $id), function() use($id){
108
            return TableFactory::getRoleModel()->find()->matching('Users', function(Query $query) use ($id){
109
                return $query->where(['Users.id' => $id]);
110
            })->toArray();
111
        });
112
    }
113
}