Completed
Push — master ( c2bc12...ef5bc2 )
by Dmitry
04:55
created

BillController::getPaymentTypes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
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\SmartDeleteAction;
17
use hipanel\actions\ValidateFormAction;
18
use hipanel\actions\ViewAction;
19
use hipanel\filters\EasyAccessControl;
20
use hipanel\modules\client\controllers\ContactController;
21
use hipanel\modules\finance\actions\BillManagementAction;
22
use hipanel\modules\finance\forms\BillForm;
23
use hipanel\modules\finance\forms\BillImportForm;
24
use hipanel\modules\finance\forms\CurrencyExchangeForm;
25
use hipanel\modules\finance\helpers\ChargesGrouper;
26
use hipanel\modules\finance\models\ExchangeRate;
27
use hipanel\modules\finance\models\Resource;
28
use hipanel\modules\finance\providers\BillTypesProvider;
29
use hiqdev\hiart\ActiveQuery;
30
use hiqdev\hiart\Collection;
31
use Yii;
32
use yii\base\Event;
33
use yii\base\Module;
34
35
class BillController extends \hipanel\base\CrudController
36
{
37
    /**
38
     * @var BillTypesProvider
39
     */
40
    private $billTypesProvider;
41
42
    public function __construct($id, Module $module, BillTypesProvider $billTypesProvider, array $config = [])
43
    {
44
        parent::__construct($id, $module, $config);
45
46
        $this->billTypesProvider = $billTypesProvider;
47
    }
48
49 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...
50
    {
51
        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...
52
            'access-bill' => [
53
                'class' => EasyAccessControl::class,
54
                'actions' => [
55
                    'create,import,copy'    => 'bill.create',
56
                    'create-exchange'       => 'bill.create',
57
                    'update,charge-delete'  => 'bill.update',
58
                    'delete'                => 'bill.delete',
59
                    '*'                     => 'bill.read',
60
                ],
61
            ],
62
        ]);
63
    }
64
65
    public function actions()
66
    {
67
        return array_merge(parent::actions(), [
68
            'index' => [
69
                'class' => IndexAction::class,
70
                '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...
71
                    list($billTypes, $billGroupLabels) = $this->getTypesAndGroups();
72
                    $rates = $this->getExchangeRates();
73
74
                    return compact('billTypes', 'billGroupLabels', 'rates');
75
                },
76
            ],
77
            'view' => [
78
                'class' => ViewAction::class,
79
                'on beforePerform' => function (Event $event) {
80
                    /** @var \hipanel\actions\SearchAction $action */
81
                    $action = $event->sender;
82
                    $dataProvider = $action->getDataProvider();
83
                    $dataProvider->query
84
                        ->joinWith(['charges' => function (ActiveQuery $query) {
85
                            $query->joinWith('commonObject');
86
                            $query->joinWith('latestCommonObject');
87
                        }])
88
                        ->andWhere(['with_charges' => true]);
89
                },
90
                'data' => function (Action $action, array $data) {
91
                    return array_merge($data, [
92
                        'grouper' => new ChargesGrouper($data['model']->charges),
93
                    ]);
94
                },
95
            ],
96
            'validate-form' => [
97
                'class' => ValidateFormAction::class,
98
            ],
99
            'validate-bill-form' => [
100
                'class' => ValidateFormAction::class,
101
                'collection' => [
102
                    'class' => Collection::class,
103
                    'model' => new BillForm(),
104
                ],
105
            ],
106
            'create' => [
107
                'class' => BillManagementAction::class,
108
            ],
109
            'update' => [
110
                'class' => BillManagementAction::class,
111
            ],
112
            'copy' => [
113
                'class' => BillManagementAction::class,
114
                'view' => 'create',
115
                'forceNewRecord' => true,
116
            ],
117
            'delete' => [
118
                'class' => SmartDeleteAction::class,
119
                'success' => Yii::t('hipanel:finance', 'Payment was deleted successfully'),
120
            ],
121
            'charge-delete' => [
122
                'class' => SmartDeleteAction::class,
123
                'success' => Yii::t('hipanel:finance', 'Charge was deleted successfully'),
124
                'collection' => [
125
                    'class'     => Collection::class,
126
                    'model'     => new Resource(['scenario' => 'delete']),
127
                    'scenario'  => 'delete',
128
                ],
129
            ],
130
            'requisites' => [
131
                'class' => RedirectAction::class,
132
                '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...
133
                    $identity = Yii::$app->user->identity;
134
                    $seller = $identity->type === $identity::TYPE_RESELLER ? $identity->username : $identity->seller;
135
                    if ($seller === 'bullet') {
136
                        $seller = 'dsr';
137
                    }
138
139
                    return array_merge(ContactController::getSearchUrl(['client' => $seller]), ['representation' => 'requisites']);
140
                },
141
            ],
142
        ]);
143
    }
144
145
    public function actionImport()
146
    {
147
        $model = new BillImportForm([
148
            'billTypes' => array_filter($this->getPaymentTypes(), function ($key) {
149
                // Kick out items that are categories names, but not real types
150
                return strpos($key, ',') !== false;
151
            }, ARRAY_FILTER_USE_KEY),
152
        ]);
153
154
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
155
            $models = $model->parse();
156
157
            if ($models !== false) {
158
                $models = BillForm::createMultipleFromBills($models, 'create');
159
                list($billTypes, $billGroupLabels) = $this->getTypesAndGroups();
160
161
                return $this->render('create', [
162
                    'models' => $models,
163
                    'model' => reset($models),
164
                    'billTypes' => $billTypes,
165
                    'billGroupLabels' => $billGroupLabels,
166
                ]);
167
            }
168
        }
169
170
        return $this->render('import', ['model' => $model]);
171
    }
172
173
    public function actionCreateExchange()
174
    {
175
        $model = new CurrencyExchangeForm();
176
177
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
178
            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...
179
                Yii::$app->session->addFlash('success', Yii::t('hipanel:finance', 'Currency was exchanged successfully'));
180
181
                return $this->redirect(['@bill']);
182
            }
183
        }
184
185
        return $this->render('create-exchange', [
186
            'model' => $model,
187
            'rates' => $this->getExchangeRates(),
188
        ]);
189
    }
190
191
    /**
192
     * @return array
193
     */
194
    public function getPaymentTypes()
195
    {
196
        return $this->billTypesProvider->getTypesList();
197
    }
198
199
    /**
200
     * @return array
201
     */
202
    private function getTypesAndGroups()
203
    {
204
        return $this->billTypesProvider->getGroupedList();
205
    }
206
207
    private function getExchangeRates()
208
    {
209
        return Yii::$app->cache->getOrSet(['exchange-rates', Yii::$app->user->id], function () {
210
            return ExchangeRate::find()->select(['from', 'to', 'rate'])->all();
211
        }, 3600);
212
    }
213
}
214