Completed
Pull Request — master (#4)
by
unknown
02:33
created

byLevel   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getLevels() 0 9 2
A getLevel() 0 7 2
1
<?php
2
3
namespace Jasny\Authz;
4
5
/**
6
 * Authorize by access level.
7
 * 
8
 * IMPORTANT: Your user class also needs to implement Jasny\Authz\User
9
 * <code>
10
 *   class User implements Jasny\Auth\User, Jasny\Authz\User
11
 *   {
12
 *     ...
13
 *   
14
 *     public function hasRole($role)
15
 *     {
16
 *       return Auth::getLevel($role) &lt;= $this->accessLevel;
17
 *     }
18
 *   }
19
 * </code>
20
 */
21
trait byLevel
22
{
23
    /**
24
     * Authorization levels.
25
     * Level names should not contain only digits.
26
     * 
27
     * <code>
28
     *   protected static $levels = [
29
     *     'user' => 1,
30
     *     'moderator' => 100,
31
     *     'admin' => 1000
32
     *   ];
33
     * </code>
34
     * 
35
     * @var array
36
     */
37
    protected static $levels;
38
    
39
    
40
    /**
41
     * Get all access levels.
42
     *  
43
     * @return array
44
     */
45
    public static function getLevels()
46
    {
47
        if (!isset(static::$levels)) {
48
            trigger_error("Auth levels aren't set", E_USER_WARNING);
49
            return [];
50
        }
51
        
52
        return static::$levels;
53
    }
54
    
55
    /**
56
     * Get access level
57
     * 
58
     * @param string $name  Level name
59
     * @return int
60
     */
61
    public static function getLevel($name)
62
    {
63
        $levels = static::getLevels();
64
        if (!isset($levels[$name])) throw new \Exception("Authorization level '$name' isn't defined.");
65
        
66
        return $levels[$name];
67
    }
68
}
69