BillController::actionImport()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 27
ccs 0
cts 22
cp 0
rs 9.488
cc 4
nc 3
nop 0
crap 20
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\controllers;
12
13
use hipanel\actions\Action;
14
use hipanel\actions\IndexAction;
15
use hipanel\actions\RedirectAction;
16
use hipanel\actions\SmartCreateAction;
17
use hipanel\actions\SmartDeleteAction;
18
use hipanel\actions\ValidateFormAction;
19
use hipanel\actions\ViewAction;
20
use hipanel\filters\EasyAccessControl;
21
use hipanel\modules\client\controllers\ContactController;
22
use hipanel\modules\finance\actions\BillManagementAction;
23
use hipanel\modules\finance\forms\BillForm;
24
use hipanel\modules\finance\forms\BillImportForm;
25
use hipanel\modules\finance\forms\CurrencyExchangeForm;
26
use hipanel\modules\finance\helpers\ChargesGrouper;
27
use hipanel\modules\finance\models\ExchangeRate;
28
use hipanel\modules\finance\models\Resource;
29
use hipanel\modules\finance\providers\BillTypesProvider;
30
use hiqdev\hiart\ActiveQuery;
31
use hiqdev\hiart\Collection;
32
use Yii;
33
use yii\base\Event;
34
use yii\base\Module;
35
36
class BillController extends \hipanel\base\CrudController
37
{
38
    /**
39
     * @var BillTypesProvider
40
     */
41
    private $billTypesProvider;
42
43
    public function __construct($id, Module $module, BillTypesProvider $billTypesProvider, array $config = [])
44
    {
45
        parent::__construct($id, $module, $config);
46
47
        $this->billTypesProvider = $billTypesProvider;
48
    }
49
50 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...
51
    {
52
        return array_merge(parent::behaviors(), [
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array_merge(paren...'*' => 'bill.read')))); (array<*,array>) is incompatible with the return type of the parent method hipanel\base\Controller::behaviors of type array[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
53
            'access-bill' => [
54
                'class' => EasyAccessControl::class,
55
                'actions' => [
56
                    'create,copy'           => 'bill.create',
57
                    'create-transfer'       => 'bill.create',
58
                    'import'                => 'bill.import',
59
                    'update,charge-delete'  => 'bill.update',
60
                    'delete'                => 'bill.delete',
61
                    '*'                     => 'bill.read',
62
                ],
63
            ],
64
        ]);
65
    }
66
67
    public function actions()
68
    {
69
        return array_merge(parent::actions(), [
70
            'index' => [
71
                'class' => IndexAction::class,
72
                'data' => function ($action) {
0 ignored issues
show
Unused Code introduced by
The parameter $action is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
73
                    list($billTypes, $billGroupLabels) = $this->getTypesAndGroups();
74
                    $rates = $this->getExchangeRates();
75
76
                    return compact('billTypes', 'billGroupLabels', 'rates');
77
                },
78
            ],
79
            'view' => [
80
                'class' => ViewAction::class,
81
                'on beforePerform' => function (Event $event) {
82
                    /** @var \hipanel\actions\SearchAction $action */
83
                    $action = $event->sender;
84
                    $dataProvider = $action->getDataProvider();
85
                    $dataProvider->query
86
                        ->joinWith(['charges' => function (ActiveQuery $query) {
87
                            $query->joinWith('commonObject');
88
                            $query->joinWith('latestCommonObject');
89
                        }])
90
                        ->andWhere(['with_charges' => true]);
91
                },
92
                'data' => function (Action $action, array $data) {
93
                    return array_merge($data, [
94
                        'grouper' => new ChargesGrouper($data['model']->charges),
95
                    ]);
96
                },
97
            ],
98
            'validate-form' => [
99
                'class' => ValidateFormAction::class,
100
            ],
101
            'validate-bill-form' => [
102
                'class' => ValidateFormAction::class,
103
                'collection' => [
104
                    'class' => Collection::class,
105
                    'model' => new BillForm(),
106
                ],
107
            ],
108
            'create' => [
109
                'class' => BillManagementAction::class,
110
            ],
111
            'update' => [
112
                'class' => BillManagementAction::class,
113
            ],
114
            'copy' => [
115
                'class' => BillManagementAction::class,
116
                'view' => 'create',
117
                'scenario' => 'create',
118
                'forceNewRecord' => true,
119
            ],
120
            'create-transfer' => [
121
                'class' => SmartCreateAction::class,
122
                'success' => Yii::t('hipanel:finance', 'Transfer was completed'),
123
                'POST html' => [
124
                    'save' => true,
125
                    'success' => [
126
                        'class' => RedirectAction::class,
127
                        'url' => function ($action) {
0 ignored issues
show
Unused Code introduced by
The parameter $action is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
128
                            return ['@bill/index'];
129
                        },
130
                    ],
131
                ],
132
            ],
133
            'delete' => [
134
                'class' => SmartDeleteAction::class,
135
                'success' => Yii::t('hipanel:finance', 'Payment was deleted successfully'),
136
            ],
137
            'charge-delete' => [
138
                'class' => SmartDeleteAction::class,
139
                'success' => Yii::t('hipanel:finance', 'Charge was deleted successfully'),
140
                'collection' => [
141
                    'class'     => Collection::class,
142
                    'model'     => new Resource(['scenario' => 'delete']),
143
                    'scenario'  => 'delete',
144
                ],
145
            ],
146
            'requisites' => [
147
                'class' => RedirectAction::class,
148
                'url' => function ($action) {
0 ignored issues
show
Unused Code introduced by
The parameter $action is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
149
                    $identity = Yii::$app->user->identity;
150
                    $seller = $identity->type === $identity::TYPE_RESELLER ? $identity->username : $identity->seller;
151
                    if ($seller === 'bullet') {
152
                        $seller = 'dsr';
153
                    }
154
155
                    return array_merge(ContactController::getSearchUrl(['client' => $seller]), ['representation' => 'requisites']);
156
                },
157
            ],
158
        ]);
159
    }
160
161
    public function actionImport()
162
    {
163
        $model = new BillImportForm([
164
            'billTypes' => array_filter($this->getPaymentTypes(), function ($key) {
165
                // Kick out items that are categories names, but not real types
166
                return strpos($key, ',') !== false;
167
            }, ARRAY_FILTER_USE_KEY),
168
        ]);
169
170
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
171
            $models = $model->parse();
172
173
            if ($models !== false) {
174
                $models = BillForm::createMultipleFromBills($models, 'create');
175
                list($billTypes, $billGroupLabels) = $this->getTypesAndGroups();
176
177
                return $this->render('create', [
178
                    'models' => $models,
179
                    'model' => reset($models),
180
                    'billTypes' => $billTypes,
181
                    'billGroupLabels' => $billGroupLabels,
182
                ]);
183
            }
184
        }
185
186
        return $this->render('import', ['model' => $model]);
187
    }
188
189
    public function actionCreateExchange()
190
    {
191
        $model = new CurrencyExchangeForm();
192
        $canSupport = Yii::$app->user->can('support');
193
        if (!$canSupport) {
194
            $model->client_id = Yii::$app->user->identity->getId();
195
        }
196
197
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
198
            if ($id = $model->save()) {
0 ignored issues
show
Unused Code introduced by
$id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
199
                Yii::$app->session->addFlash('success', Yii::t('hipanel:finance', 'Currency was exchanged successfully'));
200
201
                return $this->redirect(['@bill']);
202
            }
203
        }
204
        return $this->render('create-exchange', [
205
            'model' => $model,
206
            'canSupport' => $canSupport,
207
            'rates' => $this->getExchangeRates(),
208
        ]);
209
    }
210
211
    /**
212
     * @return array
213
     */
214
    public function getPaymentTypes()
215
    {
216
        return $this->billTypesProvider->getTypesList();
217
    }
218
219
    /**
220
     * @return array
221
     */
222
    private function getTypesAndGroups()
223
    {
224
        return $this->billTypesProvider->getGroupedList();
225
    }
226
227
    private function getExchangeRates()
228
    {
229
        return Yii::$app->cache->getOrSet(['exchange-rates', Yii::$app->user->id], function () {
230
            return ExchangeRate::find()->select(['from', 'to', 'rate'])->all();
231
        }, 3600);
232
    }
233
}
234