Completed
Push — master ( 1f4231...1ce40e )
by Charles
01:37
created

AclAction   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 4
dl 0
loc 39
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
C run() 0 23 7
1
<?php
2
3
namespace yrc\rest;
4
5
use yrc\rest\Action;
6
use Yii;
7
8
use yii\web\ForbiddenHttpException;
9
use yii\web\UnauthorizedHttpException;
10
use yii\web\HttpException;
11
12
abstract class AclAction extends Action
13
{
14
    /**
15
     * Access Control List
16
     * @var array $acl
17
     */
18
    public $acl = [];
19
20
    /**
21
     * Action runner
22
     *
23
     * @param array $args
24
     * @return mixed
25
     * @throws HttpException
26
     */
27
    public function run(array $args = [])
28
    {
29
        $method = strtolower(Yii::$app->request->method);
30
        
31
        // If the requested HTTP method exists AND an ACL is defined for it, apply ACL rules
32
        if (isset($this->acl[$method]) && method_exists(get_called_class(), $method)) {
33
            foreach ($this->acl[$method] as $role) {
34
                // @ is a special symbol meaning a user must be authenticated
35
                if ($role === '@') {
36
                    if (Yii::$app->user->isGuest) {
37
                        throw new UnauthorizedHttpException;
38
                    }
39
                } else {
40
                    // All other items are considered to be a role or permissions within RBAC
41
                    if (!Yii::$app->user->can($role)) {
42
                        throw new ForbiddenHttpException;
43
                    }
44
                }
45
            }
46
        }
47
48
        return parent::run($args);
49
    }
50
}