RoleTrait::revokeAllPermissions()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
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\Datasource\Exception\RecordNotFoundException;
10
use Cake\ORM\Query;
11
use Cake\Utility\Text;
12
use Slince\CakePermission\Constants;
13
use Slince\CakePermission\Exception\InvalidArgumentException;
14
use Slince\CakePermission\Model\Table\PermissionsTableTrait;
15
use Slince\CakePermission\TableFactory;
16
17
trait RoleTrait
18
{
19
    use HasPermissionTrait;
20
21
    /**
22
     * Gives the permission or an array of permissions
23
     * @param string|Permission|array $permission
24
     * @return bool
25
     */
26
    public function givePermission($permission)
27
    {
28
        $permissions = is_array($permission) ? $permission : [$permission];
29
        $permissions = array_map(function($permission){
30
            return is_string($permission) ? Permission::find($permission) : $permission;
31
        }, $permissions);
32
        $this->set('permissions', $permissions);
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...
33
        $result = TableFactory::getRoleModel()->save($this) !== false;
34
        PermissionsTableTrait::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...
35
        return $result;
36
    }
37
38
    /**
39
     * Revokes the permissions of the role
40
     * @param $permission
41
     * @return
42
     */
43
    public function revokePermission($permission)
44
    {
45
        if (is_string($permission)) {
46
            $permission = Permission::find($permission);
47
        }
48
        $result = TableFactory::getRoleModel()->association('Permissions')->unlink($this, [$permission]);
49
        PermissionsTableTrait::refreshCache($this->id);
50
        return $result;
51
    }
52
53
    /**
54
     * Revokes all permissions of the role
55
     * @return boolean
56
     */
57
    public function revokeAllPermissions()
58
    {
59
        $result = TableFactory::getRoleModel()->association('Permissions')->unlink($this,
60
            $this->getAllPermissions());
61
        PermissionsTableTrait::refreshCache($this->id);
62
        return $result;
63
    }
64
65
    /**
66
     * Gets all permissions for the role
67
     * @return Permission[]
68
     */
69
    public function getAllPermissions()
70
    {
71
        $primaryKey = TableFactory::getRoleModel()->getPrimaryKey();
72
        $id = $this->get($primaryKey);
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...
73
        return Cache::remember(sprintf(Constants::CACHE_PERMISSIONS, $id), function() use ($id){
74
            return TableFactory::getPermissionModel()->find()->matching('Roles', function(Query $query) use ($id){
75
                return $query->where(['Roles.id' => $id]);
76
            })->toArray();
77
        });
78
    }
79
80
    /**
81
     * Finds the role by its name
82
     * @param string $name
83
     * @return RoleTrait
0 ignored issues
show
Comprehensibility Bug introduced by
The return type RoleTrait is a trait, and thus cannot be used for type-hinting in PHP. Maybe consider adding an interface and use that for type-hinting?

In PHP traits cannot be used for type-hinting as they do not define a well-defined structure. This is because any class that uses a trait can rename that trait’s methods.

If you would like to return an object that has a guaranteed set of methods, you could create a companion interface that lists these methods explicitly.

Loading history...
84
     */
85
    public static function find($name)
86
    {
87
        return TableFactory::getRoleModel()->findByName($name)->firstOrFail();
88
    }
89
90
    /**
91
     * Creates a role
92
     * @param $arguments
93
     * @return RoleTrait
0 ignored issues
show
Comprehensibility Bug introduced by
The return type RoleTrait is a trait, and thus cannot be used for type-hinting in PHP. Maybe consider adding an interface and use that for type-hinting?

In PHP traits cannot be used for type-hinting as they do not define a well-defined structure. This is because any class that uses a trait can rename that trait’s methods.

If you would like to return an object that has a guaranteed set of methods, you could create a companion interface that lists these methods explicitly.

Loading history...
94
     */
95
    public static function create($arguments)
96
    {
97
        if (is_string($arguments)) {
98
            $arguments = [
99
                'name' => $arguments
100
            ];
101
        }
102
        $arguments['slug'] = Text::slug($arguments['name']);
103
        $role = TableFactory::getRoleModel()->newEntity($arguments, ['validate' => 'permission']);
104
        if (TableFactory::getRoleModel()->save($role) === false) {
105
            throw new InvalidArgumentException('Failed to create the role');
106
        }
107
        return $role;
108
    }
109
110
    /**
111
     * Finds the role, if it does not exists, the role will be created
112
     * @param $name
113
     * @return RoleTrait
0 ignored issues
show
Comprehensibility Bug introduced by
The return type RoleTrait is a trait, and thus cannot be used for type-hinting in PHP. Maybe consider adding an interface and use that for type-hinting?

In PHP traits cannot be used for type-hinting as they do not define a well-defined structure. This is because any class that uses a trait can rename that trait’s methods.

If you would like to return an object that has a guaranteed set of methods, you could create a companion interface that lists these methods explicitly.

Loading history...
114
     */
115
    public static function findOrCreate($name)
116
    {
117
        try {
118
            $role = static::find($name);
119
        } catch (RecordNotFoundException $exception) {
120
            $role = static::create($name);
121
        }
122
        return $role;
123
    }
124
}