Completed
Push — master ( 4f1415...383c20 )
by Dmitry
05:05
created

PlanController   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 154
Duplicated Lines 9.09 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 11
dl 14
loc 154
c 0
b 0
f 0
ccs 0
cts 127
cp 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A behaviors() 14 14 1
A actions() 0 62 1
A actionCreatePrices() 0 10 2
A actionTemplates() 0 11 1
B actionCalculateCharges() 0 46 4

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\controllers;
4
5
use hipanel\actions\Action;
6
use hipanel\actions\IndexAction;
7
use hipanel\actions\SmartCreateAction;
8
use hipanel\actions\SmartDeleteAction;
9
use hipanel\actions\SmartPerformAction;
10
use hipanel\actions\SmartUpdateAction;
11
use hipanel\actions\ValidateFormAction;
12
use hipanel\actions\ViewAction;
13
use hipanel\base\CrudController;
14
use hipanel\modules\finance\helpers\PlanInternalsGrouper;
15
use hipanel\modules\finance\models\Plan;
16
use hipanel\filters\EasyAccessControl;
17
use hiqdev\hiart\Query;
18
use Money\Currencies\ISOCurrencies;
19
use Money\Currency;
20
use Money\Formatter\DecimalMoneyFormatter;
21
use Money\Formatter\IntlMoneyFormatter;
22
use Money\Money;
23
use Yii;
24
use yii\base\Event;
25
use yii\web\NotFoundHttpException;
26
use yii\web\Response;
27
28
class PlanController extends CrudController
29
{
30 View Code Duplication
    public function behaviors()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
31
    {
32
        return array_merge(parent::behaviors(), [
33
            [
34
                'class' => EasyAccessControl::class,
35
                'actions' => [
36
                    'create' => 'plan.create',
37
                    'update' => 'plan.update',
38
                    'templates' => 'plan.create',
39
                    '*' => 'plan.read',
40
                ],
41
            ],
42
        ]);
43
    }
44
45
    public function actions()
46
    {
47
        return array_merge(parent::actions(), [
48
            'create' => [
49
                'class' => SmartCreateAction::class,
50
                'success' => Yii::t('hipanel.finance.plan', 'Plan was successfully created')
51
            ],
52
            'update' => [
53
                'class' => SmartUpdateAction::class,
54
                'success' => Yii::t('hipanel.finance.plan', 'Plan was successfully updated')
55
            ],
56
            'index' => [
57
                'class' => IndexAction::class,
58
            ],
59
            'view' => [
60
                'class' => ViewAction::class,
61
                'on beforePerform' => function (Event $event) {
62
                    $action = $event->sender;
63
                    $action->getDataProvider()->query
64
                        ->joinWith('sales')
65
                        ->andWhere(['state' => ['ok', 'deleted']])
66
                        ->with([
67
                            'prices' => function (Query $query) {
68
                                $query
69
                                    ->addSelect('main_object_id')
70
                                    ->joinWith('object')
71
                                    ->limit('ALL');
72
                            },
73
                        ]);
74
                },
75
                'data' => function (Action $action, array $data) {
76
                    return array_merge($data, [
77
                        'grouper' => new PlanInternalsGrouper($data['model']),
78
                    ]);
79
                },
80
            ],
81
            'set-note' => [
82
                'class' => SmartUpdateAction::class,
83
                'success' => Yii::t('hipanel', 'Note changed'),
84
            ],
85
            'validate-form' => [
86
                'class' => ValidateFormAction::class,
87
            ],
88
            'validate-single-form' => [
89
                'class' => ValidateFormAction::class,
90
                'validatedInputId' => false,
91
            ],
92
            'delete' => [
93
                'class' => SmartDeleteAction::class,
94
                'success' => Yii::t('hipanel.finance.plan', 'Plan was successfully deleted')
95
            ],
96
            'restore' => [
97
                'class' => SmartPerformAction::class,
98
                'success' => Yii::t('hipanel.finance.plan', 'Plan was successfully restored')
99
            ],
100
            'copy' => [
101
                'class' => SmartUpdateAction::class,
102
                'view' => 'modals/copy',
103
                'queryOptions' => ['batch' => false],
104
            ],
105
        ]);
106
    }
107
108
    public function actionCreatePrices($id)
109
    {
110
        $plan = Plan::findOne(['id' => $id]);
111
        if ($plan === null) {
112
            throw new NotFoundHttpException('Not found');
113
        }
114
        $this->layout = false;
115
116
        return $this->renderAjax('_createPrices', ['plan' => $plan]);
117
    }
118
119
    /**
120
     * @param string $object_id
121
     * @param string $plan_id
122
     */
123
    public function actionTemplates($plan_id, $object_id)
124
    {
125
        $templates = (new Plan())->query('search-templates', [
126
            'id' => $plan_id,
127
            'object_id' => $object_id,
128
        ]);
129
130
        Yii::$app->response->format = Response::FORMAT_JSON;
131
132
        return $templates;
133
    }
134
135
    public function actionCalculateCharges()
136
    {
137
        $request = Yii::$app->request;
138
139
        $response = Plan::perform('calculate-charges', [
140
            'actions' => $request->post('actions'),
141
            'prices' => $request->post('prices'),
142
            'times' => [
143
                'now',
144
                'first day of +1 month',
145
                'first day of +2 month',
146
            ],
147
        ]);
148
149
        $moneyFormatter = new DecimalMoneyFormatter(new ISOCurrencies());
150
151
        $result = [];
152
        foreach ($response as $time => $charges) {
153
            $chargesByTarget = [];
154
155
            foreach ($charges as $charge) {
156
                $action = $charge['action'];
157
                $targetId = $action['target']['id'];
158
                if (empty($targetId)) {
159
                    Yii::warning('Action does not contain target ID');
160
                    continue;
161
                }
162
                $actionType = $action['type']['name'];
163
164
                $price = $charge['price'];
165
                $priceType = $price['type']['name'];
166
167
                $chargesByTarget[$targetId][$actionType][] = [
168
                    'price' => $moneyFormatter->format(
169
                        new Money($price['price']['amount'], new Currency($price['price']['currency']))
170
                    ),
171
                    'type' => $priceType
172
                ];
173
            }
174
175
            $result[date('m Y', strtotime($time))] = $chargesByTarget;
176
        }
177
178
        Yii::$app->response->format = Response::FORMAT_JSON;
179
        return $result;
180
    }
181
}
182