Completed
Push — master ( 62d2ea...1993b9 )
by Andrii
11:09
created

BillManagementAction   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 149
Duplicated Lines 4.03 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 11
dl 6
loc 149
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A init() 0 8 2
A run() 0 18 2
A findBills() 0 12 2
C getRequestedIds() 0 23 8
A createCollection() 0 18 2
B saveBills() 0 24 6
A addSuccessFlash() 6 10 3

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
namespace hipanel\modules\finance\actions;
4
5
use hipanel\modules\finance\forms\BillForm;
6
use hipanel\modules\finance\forms\BillImportForm;
7
use hipanel\modules\finance\models\Bill;
8
use hipanel\modules\finance\providers\BillTypesProvider;
9
use hiqdev\hiart\Collection;
10
use hiqdev\hiart\ResponseErrorException;
11
use Yii;
12
use yii\base\Action;
13
use yii\web\Controller;
14
use yii\web\Response;
15
16
class BillManagementAction extends Action
17
{
18
    /**
19
     * @var \yii\web\Request
20
     */
21
    protected $request;
22
23
    /**
24
     * @var Collection
25
     */
26
    protected $collection;
27
    /**
28
     * @var BillTypesProvider
29
     */
30
    private $billTypesProvider;
31
32
    /**
33
     * @var string
34
     */
35
    public $scenario;
36
37
    public function __construct($id, Controller $controller, BillTypesProvider $billTypesProvider, array $config = [])
38
    {
39
        parent::__construct($id, $controller, $config);
40
41
        $this->request = Yii::$app->request;
42
        $this->billTypesProvider = $billTypesProvider;
43
    }
44
45
    public function init()
46
    {
47
        parent::init();
48
49
        if (!isset($this->scenario)) {
50
            $this->scenario = $this->id;
51
        }
52
    }
53
54
    public function run()
55
    {
56
        $this->createCollection();
57
        $this->findBills();
58
59
        $result = $this->saveBills();
60
        if ($result instanceof Response) {
61
            return $result;
62
        }
63
64
        list($billTypes, $billGroupLabels) = $this->billTypesProvider->getGroupedList();
65
66
        return $this->controller->render($this->scenario, [
67
            'models' => $this->collection->getModels(),
68
            'billTypes' => $billTypes,
69
            'billGroupLabels' => $billGroupLabels
70
        ]);
71
    }
72
73
    private function findBills()
74
    {
75
        $ids = $this->getRequestedIds();
76
77
        if ($ids === false) {
78
            return;
79
        }
80
81
        $bills = Bill::find()->joinWith('charges')->where(['ids' => $ids, 'with_charges' => true])->all();
82
        $billForms = BillForm::createMultipleFromBills($bills, BillForm::SCENARIO_UPDATE);
83
        $this->collection->set($billForms);
84
    }
85
86
    private function getRequestedIds()
87
    {
88
        $request = $this->request;
89
90
        if ($request->isPost && ($ids = $request->post('selection')) !== null) {
91
            return $ids;
92
        }
93
94
        if ($request->isGet && ($id = $request->get('id')) !== null) {
95
            return [$id];
96
        }
97
98
        if ($request->isPost && $request->post('BillForm') !== null) {
99
            return false;
100
        }
101
102
        if ($this->scenario === BillForm::SCENARIO_CREATE) {
103
            $this->collection->set([new BillForm(['scenario' => $this->scenario])]);
104
            return true;
105
        }
106
107
        throw new \yii\web\UnprocessableEntityHttpException('Id is missing');
108
    }
109
110
    private function createCollection()
111
    {
112
        $this->collection = new Collection([
113
            'model' => new BillForm(['scenario' => $this->scenario]),
114
            'scenario' => $this->scenario,
115
            'loadFormatter' => function ($baseModel, $key, $value) {
116
                /** @var BillForm $baseModel */
117
                $charges = $this->request->post($baseModel->newCharge()->formName());
118
                $value['charges'] = isset($charges[$key]) ? $charges[$key] : [];
119
120
                return [$key, $value];
121
            },
122
            'dataCollector' => function ($model) {
123
                /** @var BillForm $model */
124
                return [$model->getPrimaryKey(), $model->toArray()];
125
            }
126
        ]);
127
    }
128
129
    private function saveBills()
130
    {
131
        $request = $this->request;
132
        $collection = $this->collection;
133
134
        if (
135
            $request->isPost
136
            && ($payload = $request->post($this->collection->formName)) !== null
137
            && $collection->load($payload)
138
            && $collection->validate()
139
        ) {
140
            try {
141
                $collection->save();
142
                $this->addSuccessFlash();
143
144
                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.

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...
145
            } catch (ResponseErrorException $e) {
146
                Yii::$app->session->addFlash('error', $e->getMessage());
147
                return false;
148
            }
149
        }
150
151
        return null;
152
    }
153
154
    private function addSuccessFlash()
155
    {
156 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...
157
            return Yii::$app->session->addFlash('success', Yii::t('hipanel:finance', 'Bill was created successfully'));
158
        }
159
160 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...
161
            return Yii::$app->session->addFlash('success', Yii::t('hipanel:finance', 'Bill was updated successfully'));
162
        }
163
    }
164
}
165