BillManagementAction   A
last analyzed

Complexity

Total Complexity 32

Size/Duplication

Total Lines 182
Duplicated Lines 3.3 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 10
dl 6
loc 182
ccs 0
cts 112
cp 0
rs 9.84
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A init() 0 8 3
A run() 0 18 2
A findBills() 0 17 4
B getRequestedIds() 0 24 8
A createCollection() 0 18 2
B saveBills() 0 25 6
A addSuccessFlash() 6 10 3
A getView() 0 4 2
A setView() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Finance module for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-finance
6
 * @package   hipanel-module-finance
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\finance\actions;
12
13
use hipanel\modules\finance\forms\BillForm;
14
use hipanel\modules\finance\models\Bill;
15
use hipanel\modules\finance\providers\BillTypesProvider;
16
use hiqdev\hiart\Collection;
17
use hiqdev\hiart\ResponseErrorException;
18
use Yii;
19
use yii\base\Action;
20
use yii\web\Controller;
21
use yii\web\Response;
22
23
class BillManagementAction extends Action
24
{
25
    /**
26
     * @var \yii\web\Request
27
     */
28
    protected $request;
29
30
    /**
31
     * @var Collection
32
     */
33
    protected $collection;
34
    /**
35
     * @var BillTypesProvider
36
     */
37
    private $billTypesProvider;
38
39
    /**
40
     * @var string
41
     */
42
    public $scenario;
43
44
    /**
45
     * @var string The view that represents current update action
46
     */
47
    public $_view;
48
49
    /**
50
     * @var bool
51
     */
52
    public $forceNewRecord = false;
53
54
    public function __construct($id, Controller $controller, BillTypesProvider $billTypesProvider, array $config = [])
55
    {
56
        parent::__construct($id, $controller, $config);
57
58
        $this->request = Yii::$app->request;
59
        $this->billTypesProvider = $billTypesProvider;
60
    }
61
62
    public function init()
63
    {
64
        parent::init();
65
66
        if (!isset($this->scenario) || !in_array($this->scenario, [BillForm::SCENARIO_CREATE, BillForm::SCENARIO_UPDATE, BillForm::SCENARIO_COPY], true)) {
67
            $this->scenario = $this->id;
68
        }
69
    }
70
71
    public function run()
72
    {
73
        $this->createCollection();
74
        $this->findBills();
75
76
        $result = $this->saveBills();
77
        if ($result instanceof Response) {
78
            return $result;
79
        }
80
81
        list($billTypes, $billGroupLabels) = $this->billTypesProvider->getGroupedList();
82
83
        return $this->controller->render($this->view, [
0 ignored issues
show
Documentation introduced by
The property view does not exist on object<hipanel\modules\f...s\BillManagementAction>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
84
            'models' => $this->collection->getModels(),
85
            'billTypes' => $billTypes,
86
            'billGroupLabels' => $billGroupLabels,
87
        ]);
88
    }
89
90
    private function findBills()
91
    {
92
        $ids = $this->getRequestedIds();
93
94
        if ($ids === false) {
95
            return;
96
        }
97
98
        $bills = Bill::find()->joinWith('charges')->where(['ids' => $ids, 'with_charges' => true])->all();
99
        $billForms = BillForm::createMultipleFromBills($bills, $this->scenario);
100
        if ($this->forceNewRecord === true) {
101
            foreach ($billForms as $model) {
102
                $model->forceNewRecord();
103
            }
104
        }
105
        $this->collection->set($billForms);
106
    }
107
108
    private function getRequestedIds()
109
    {
110
        $request = $this->request;
111
112
        if ($request->isPost && ($ids = $request->post('selection')) !== null) {
113
            return $ids;
114
        }
115
116
        if ($request->isGet && ($id = $request->get('id')) !== null) {
117
            return [$id];
118
        }
119
120
        if ($request->isPost && $request->post('BillForm') !== null) {
121
            return false;
122
        }
123
124
        if ($this->scenario === BillForm::SCENARIO_CREATE) {
125
            $this->collection->set([new BillForm(['scenario' => $this->scenario])]);
126
127
            return true;
128
        }
129
130
        throw new \yii\web\UnprocessableEntityHttpException('Id is missing');
131
    }
132
133
    private function createCollection()
134
    {
135
        $this->collection = new Collection([
136
            'model' => new BillForm(['scenario' => $this->scenario]),
137
            'scenario' => $this->scenario,
138
            'loadFormatter' => function ($baseModel, $key, $value) {
139
                /** @var BillForm $baseModel */
140
                $charges = $this->request->post($baseModel->newCharge()->formName());
141
                $value['charges'] = isset($charges[$key]) ? $charges[$key] : [];
142
143
                return [$key, $value];
144
            },
145
            'dataCollector' => function ($model) {
146
                /** @var BillForm $model */
147
                return [$model->getPrimaryKey(), $model->toArray()];
148
            },
149
        ]);
150
    }
151
152
    private function saveBills()
153
    {
154
        $request = $this->request;
155
        $collection = $this->collection;
156
157
        if (
158
            $request->isPost
159
            && ($payload = $request->post($this->collection->formName)) !== null
160
            && $collection->load($payload)
161
            && $collection->validate()
162
        ) {
163
            try {
164
                $collection->save();
165
                $this->addSuccessFlash();
166
167
                return $this->controller->redirect(['@bill', 'id_in' => $collection->getIds()]);
0 ignored issues
show
Bug introduced by
The method redirect does only exist in yii\web\Controller, but not in yii\base\Controller and yii\console\Controller.

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...
168
            } catch (ResponseErrorException $e) {
169
                Yii::$app->session->addFlash('error', $e->getMessage());
170
171
                return false;
172
            }
173
        }
174
175
        return null;
176
    }
177
178
    private function addSuccessFlash()
179
    {
180 View Code Duplication
        if ($this->scenario === BillForm::SCENARIO_CREATE) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
181
            return Yii::$app->session->addFlash('success', Yii::t('hipanel:finance', 'Bill was created successfully'));
182
        }
183
184 View Code Duplication
        if ($this->scenario === BillForm::SCENARIO_UPDATE) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
185
            return Yii::$app->session->addFlash('success', Yii::t('hipanel:finance', 'Bill was updated successfully'));
186
        }
187
    }
188
189
    /**
190
     * @return string
191
     */
192
    public function getView()
193
    {
194
        return $this->_view ?: $this->scenario;
195
    }
196
197
    /**
198
     * @param string $view
199
     */
200
    public function setView($view)
201
    {
202
        $this->_view = $view;
203
    }
204
}
205