Completed
Push — master ( f706eb...84b009 )
by Antonio
01:40
created

RuleController::findRule()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 6
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\Model\Rule;
15
use Da\User\Search\RuleSearch;
16
use Da\User\Service\AuthRuleEditionService;
17
use Da\User\Traits\AuthManagerAwareTrait;
18
use Da\User\Traits\ContainerAwareTrait;
19
use Da\User\Validator\AjaxRequestModelValidator;
20
use Yii;
21
use yii\filters\VerbFilter;
22
use yii\web\Controller;
23
use yii\web\NotFoundHttpException;
24
25
class RuleController extends Controller
26
{
27
    use AuthManagerAwareTrait;
28
    use ContainerAwareTrait;
29
30
    /**
31
     * @inheritdoc
32
     */
33
    public function behaviors()
34
    {
35
        return [
36
            [
37
                'class' => VerbFilter::className(),
38
                'actions' => [
39
                    'delete' => ['POST'],
40
                ],
41
            ]
42
        ];
43
    }
44
45
    public function actionIndex()
46
    {
47
        /** @var RuleSearch $searchModel */
48
        $searchModel = $this->make(RuleSearch::class);
49
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
50
51
        return $this->render(
52
            'index',
53
            [
54
                'searchModel' => $searchModel,
55
                'dataProvider' => $dataProvider,
56
            ]
57
        );
58
    }
59
60
    public function actionCreate()
61
    {
62
        $model = $this->make(Rule::class, [], ['scenario' => 'create', 'className' => \yii\rbac\Rule::class]);
63
64
        $this->make(AjaxRequestModelValidator::class, [$model])->validate();
65
66
        if ($model->load(Yii::$app->request->post())) {
67
            if ($this->make(AuthRuleEditionService::class, [$model])->run()) {
68
                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...
69
70
                return $this->redirect(['index']);
71
            }
72
            Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Unable to create new authorization rule.'));
73
        }
74
75
        return $this->render(
76
            'create',
77
            [
78
                'model' => $model
79
            ]
80
        );
81
    }
82
83
    public function actionUpdate($name)
84
    {
85
        /** @var Rule $model */
86
        $model = $this->make(Rule::class, [], ['scenario' => 'update']);
87
        $rule = $this->findRule($name);
88
89
        $model->setAttributes(
90
            [
91
                'previousName' => $name,
92
                'name' => $rule->name,
93
                'className' => get_class($rule)
94
            ]
95
        );
96
97
        $this->make(AjaxRequestModelValidator::class, [$model])->validate();
98
99
        if ($model->load(Yii::$app->request->post())) {
100
            if ($this->make(AuthRuleEditionService::class, [$model])->run()) {
101
                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...
102
103
                return $this->redirect(['index']);
104
            }
105
            Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Unable to update authorization rule.'));
106
        }
107
108
        return $this->render(
109
            'update',
110
            [
111
                'model' => $model,
112
            ]
113
        );
114
    }
115
116
    public function actionDelete($name)
117
    {
118
        $rule = $this->findRule($name);
119
120
        $this->getAuthManager()->remove($rule);
121
        $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...
122
123
        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...
124
    }
125
126
    /**
127
     * @param $name
128
     *
129
     * @throws NotFoundHttpException
130
     * @return mixed|null|\yii\rbac\Rule
131
     */
132
    protected function findRule($name)
133
    {
134
        $rule = $this->getAuthManager()->getRule($name);
135
136
        if (!($rule instanceof \yii\rbac\Rule)) {
137
            throw new NotFoundHttpException(Yii::t('usuario', 'Rule {0} not found.', $name));
138
        }
139
140
        return $rule;
141
    }
142
}
143