PermissionTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 4
dl 0
loc 48
c 0
b 0
f 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A find() 0 4 1
A create() 0 15 3
A findOrCreate() 0 9 2
1
<?php
2
/**
3
 * CakePHP permission handling library
4
 * @author Tao <[email protected]>
5
 */
6
namespace Slince\CakePermission\Model\Entity;
7
8
use Cake\Datasource\Exception\RecordNotFoundException;
9
use Cake\Utility\Text;
10
use Slince\CakePermission\Exception\InvalidArgumentException;
11
use Slince\CakePermission\TableFactory;
12
13
trait PermissionTrait
14
{
15
    /**
16
     * Gets the permission by its name
17
     * @param $name
18
     * @return Permission
19
     */
20
    public static function find($name)
21
    {
22
        return TableFactory::getPermissionModel()->findByName($name)->firstOrFail();
23
    }
24
25
    /**
26
     * Creates a role
27
     * @param $arguments
28
     * @return Permission
29
     */
30
    public static function create($arguments)
31
    {
32
        if (is_string($arguments)) {
33
            $arguments = [
34
                'name' => $arguments
35
            ];
36
        }
37
        $arguments['slug'] = Text::slug($arguments['name']);
38
        $permission = TableFactory::getPermissionModel()->newEntity($arguments, ['validate' => 'permission']);
39
        if (TableFactory::getPermissionModel()->save($permission) === false) {
40
            throw new InvalidArgumentException(sprintf('Failed to create the permission "%s"',
41
                $arguments['name']));
42
        }
43
        return $permission;
44
    }
45
46
    /**
47
     * Finds the permission by its name, if it does not exists, the role will be created
48
     * @param $name
49
     * @return Permission
50
     */
51
    public static function findOrCreate($name)
52
    {
53
        try {
54
            $permission = static::find($name);
55
        } catch (RecordNotFoundException $exception) {
56
            $permission = static::create($name);
57
        }
58
        return $permission;
59
    }
60
}