Passed
Branch master (b30e74)
by Alexey
05:46
created

AccessBehavior::processLogout()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 2
eloc 3
nc 2
nop 0
1
<?php
2
3
namespace modules\rbac\components\behavior;
4
5
use Yii;
6
use yii\base\Behavior;
7
use yii\console\Controller;
8
9
/**
10
 * Class AccessBehavior
11
 * @package modules\rbac\components\behavior
12
 */
13
class AccessBehavior extends Behavior
14
{
15
    /**
16
     * @var string
17
     */
18
    public $permission = '';
19
20
    /**
21
     * @var string
22
     */
23
    public $role = '';
24
25
    /**
26
     * @inheritdoc
27
     * @return array
28
     */
29
    public function events()
30
    {
31
        return [
32
            Controller::EVENT_BEFORE_ACTION => 'accessAction'
33
        ];
34
    }
35
36
    /**
37
     * @inheritdoc
38
     */
39
    public function accessAction()
40
    {
41
        if ((!empty($this->permission) && !$this->checkPermission()) || (!empty($this->role) && !$this->checkRole())) {
42
            $this->processLogout();
43
        }
44
    }
45
46
    /**
47
     * @return bool
48
     */
49
    protected function checkPermission()
50
    {
51
        if (!empty($this->permission)) {
52
            if (Yii::$app->user->can($this->permission)) {
53
                return true;
54
            }
55
        }
56
        return false;
57
    }
58
59
    /**
60
     * @return bool
61
     */
62
    protected function checkRole()
63
    {
64
        if (!empty($this->role)) {
65
            if (Yii::$app->user->can($this->role)) {
66
                return true;
67
            }
68
        }
69
        return false;
70
    }
71
72
    /**
73
     * Logout and set Flash message
74
     */
75
    private function processLogout()
76
    {
77
        if (!Yii::$app->user->isGuest) {
78
            Yii::$app->user->logout();
79
            Yii::$app->session->setFlash('error', Yii::t('app', 'You are not allowed access!'));
80
        }
81
    }
82
}
83