RuleController::actionCreate()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 18
cp 0
rs 9.568
c 0
b 0
f 0
cc 3
nc 3
nop 0
crap 12
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-usuario project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\User\Controller;
13
14
use Da\User\Filter\AccessRuleFilter;
15
use Da\User\Model\Rule;
16
use Da\User\Search\RuleSearch;
17
use Da\User\Service\AuthRuleEditionService;
18
use Da\User\Traits\AuthManagerAwareTrait;
19
use Da\User\Traits\ContainerAwareTrait;
20
use Da\User\Validator\AjaxRequestModelValidator;
21
use Yii;
22
use yii\filters\AccessControl;
23
use yii\filters\VerbFilter;
24
use yii\web\Controller;
25
use yii\web\NotFoundHttpException;
26
27
class RuleController extends Controller
28
{
29
    use AuthManagerAwareTrait;
30
    use ContainerAwareTrait;
31
32
    /**
33
     * @inheritdoc
34
     */
35
    public function behaviors()
36
    {
37
        return [
38
            'verbs' => [
39
                'class' => VerbFilter::class,
40
                'actions' => [
41
                    'delete' => ['POST'],
42
                ],
43
            ],
44
            'access' => [
45
                'class' => AccessControl::class,
46
                'ruleConfig' => [
47
                    'class' => AccessRuleFilter::class,
48
                ],
49
                'rules' => [
50
                    [
51
                        'allow' => true,
52
                        'roles' => ['admin'],
53
                    ],
54
                ],
55
            ],
56
        ];
57
    }
58
59
    public function actionIndex()
60
    {
61
        /** @var RuleSearch $searchModel */
62
        $searchModel = $this->make(RuleSearch::class);
63
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
64
65
        return $this->render(
66
            'index',
67
            [
68
                'searchModel' => $searchModel,
69
                'dataProvider' => $dataProvider,
70
            ]
71
        );
72
    }
73
74
    public function actionCreate()
75
    {
76
        $model = $this->make(Rule::class, [], ['scenario' => 'create', 'className' => \yii\rbac\Rule::class]);
77
78
        $this->make(AjaxRequestModelValidator::class, [$model])->validate();
79
80
        if ($model->load(Yii::$app->request->post())) {
81
            if ($this->make(AuthRuleEditionService::class, [$model])->run()) {
82
                Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Authorization rule has been added.'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
83
84
                return $this->redirect(['index']);
85
            }
86
            Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Unable to create new authorization rule.'));
87
        }
88
89
        return $this->render(
90
            'create',
91
            [
92
                'model' => $model
93
            ]
94
        );
95
    }
96
97
    public function actionUpdate($name)
98
    {
99
        /** @var Rule $model */
100
        $model = $this->make(Rule::class, [], ['scenario' => 'update']);
101
        $rule = $this->findRule($name);
102
103
        $model->setAttributes(
104
            [
105
                'previousName' => $name,
106
                'name' => $rule->name,
107
                'className' => get_class($rule)
108
            ]
109
        );
110
111
        $this->make(AjaxRequestModelValidator::class, [$model])->validate();
112
113
        if ($model->load(Yii::$app->request->post())) {
114
            if ($this->make(AuthRuleEditionService::class, [$model])->run()) {
115
                Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Authorization rule has been updated.'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
116
117
                return $this->redirect(['index']);
118
            }
119
            Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Unable to update authorization rule.'));
120
        }
121
122
        return $this->render(
123
            'update',
124
            [
125
                'model' => $model,
126
            ]
127
        );
128
    }
129
130
    public function actionDelete($name)
131
    {
132
        $rule = $this->findRule($name);
133
134
        $this->getAuthManager()->remove($rule);
135
        $this->getAuthManager()->invalidateCache();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\rbac\ManagerInterface as the method invalidateCache() does only exist in the following implementations of said interface: Da\User\Component\AuthDbManagerComponent, yii\rbac\DbManager.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
136
137
        Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Authorization rule has been removed.'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
138
        return $this->redirect(['index']);
139
    }
140
141
    /**
142
     * @param $name
143
     *
144
     * @throws NotFoundHttpException
145
     * @return mixed|null|\yii\rbac\Rule
146
     */
147
    protected function findRule($name)
148
    {
149
        $rule = $this->getAuthManager()->getRule($name);
150
151
        if (!($rule instanceof \yii\rbac\Rule)) {
152
            throw new NotFoundHttpException(Yii::t('usuario', 'Rule {0} not found.', $name));
153
        }
154
155
        return $rule;
156
    }
157
}
158