Completed
Push — master ( ecdd68...e69772 )
by Arnold
02:25
created

ByGroup   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 44
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getGroups() 0 4 1
A expandGroup() 0 15 4
1
<?php
2
3
namespace Jasny\Authz;
4
5
/**
6
 * Authorize by access group.
7
 * Can be used for ACL (Access Control List).
8
 * 
9
 * <code>
10
 *   class Auth extends Jasny\Auth
11
 *   {
12
 *     use Jasny\Authz\ByGroup;
13
 *
14
 *     protected $groups = [
15
 *       'user' => [],
16
 *       'developer' => ['user'],
17
 *       'accountant' => ['user'],
18
 *       'admin' => ['developer', 'accountant']
19
 *     ];
20
 *   }
21
 * </code>
22
 */
23
trait ByGroup
24
{
25
    /**
26
     * Authentication groups
27
     * @internal Overwrite this in your child class
28
     * 
29
     * @var string[]
30
     */
31
    protected $groups = [
32
        'user' => []
33
    ];
34
    
35
    /**
36
     * Get all auth groups
37
     *  
38
     * @return array
39
     */
40
    public function getGroups()
41
    {
42
        return $this->groups;
43
    }
44
    
45
    /**
46
     * Get group and all groups it embodies.
47
     *  
48
     * @param string|array $groups  Single group or array of groups
49
     * @return array
50
     */
51
    public function expandGroup($groups)
52
    {
53
        if (!is_array($groups)) $groups = (array)$groups;
54
        
55
        $allGroups = static::getGroups();
56
        $expanded = $groups;
57
        
58
        foreach ($groups as $group) {
59
            if (!empty($allGroups[$group])) {
60
                $expanded = array_merge($groups, static::expandGroup($allGroups[$group]));
61
            }
62
        }
63
        
64
        return array_unique($expanded);
65
    }
66
}
67