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

BillController::actionCreateExchange()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.2
c 0
b 0
f 0
ccs 0
cts 13
cp 0
cc 4
eloc 9
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-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\finance\controllers;
12
13
use hipanel\actions\IndexAction;
14
use hipanel\actions\RedirectAction;
15
use hipanel\actions\SmartCreateAction;
16
use hipanel\actions\SmartPerformAction;
17
use hipanel\actions\SmartUpdateAction;
18
use hipanel\actions\ValidateFormAction;
19
use hipanel\actions\ViewAction;
20
use hipanel\modules\client\controllers\ContactController;
21
use hipanel\modules\finance\actions\BillManagementAction;
22
use hipanel\modules\finance\forms\BillImportForm;
23
use hipanel\modules\finance\forms\CurrencyExchangeForm;
24
use hipanel\modules\finance\models\Bill;
25
use hipanel\modules\finance\models\ExchangeRate;
26
use hipanel\modules\finance\providers\BillTypesProvider;
27
use Yii;
28
use yii\base\Module;
29
use yii\filters\AccessControl;
30
31
class BillController extends \hipanel\base\CrudController
32
{
33
    /**
34
     * @var BillTypesProvider
35
     */
36
    private $billTypesProvider;
37
38
    public function __construct($id, Module $module, BillTypesProvider $billTypesProvider, array $config = [])
39
    {
40
        parent::__construct($id, $module, $config);
41
42
        $this->billTypesProvider = $billTypesProvider;
43
    }
44
45
    public function behaviors()
46
    {
47
        return array_merge(parent::behaviors(), [
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array_merge(paren...> array('delete')))))); (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...
48
            'access-bill' => [
49
                'class' => AccessControl::class,
50
                'only' => ['index', 'view', 'create', 'update', 'delete', 'create-exchange'],
51
                'rules' => [
52
                    [
53
                        'allow' => true,
54
                        'roles' => ['manage', 'deposit'],
55
                        'actions' => ['index', 'view'],
56
                    ],
57
                    [
58
                        'allow' => true,
59
                        'roles' => ['bill.create'],
60
                        'actions' => ['create', 'import', 'copy', 'create-exchange'],
61
                    ],
62
                    [
63
                        'allow' => true,
64
                        'roles' => ['bill.update'],
65
                        'actions' => ['update'],
66
                    ],
67
                    [
68
                        'allow' => true,
69
                        'roles' => ['bill.delete'],
70
                        'actions' => ['delete'],
71
                    ],
72
                ],
73
            ]
74
        ]);
75
    }
76
77
    public function actions()
78
    {
79
        return [
80
            'index' => [
81
                'class' => IndexAction::class,
82
                '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...
83
                    list($billTypes, $billGroupLabels) = $this->getTypesAndGroups();
84
                    $rates = $this->getExchangeRates();
85
86
                    return compact('billTypes', 'billGroupLabels', 'rates');
87
                },
88
            ],
89
            'view' => [
90
                'class' => ViewAction::class,
91
            ],
92
            'validate-form' => [
93
                'class' => ValidateFormAction::class,
94
            ],
95
            'create' => [
96
                'class' => BillManagementAction::class,
97
            ],
98
            'update' => [
99
                'class' => BillManagementAction::class,
100
            ],
101
            'copy' => [
102
                'class' => SmartUpdateAction::class,
103
                'scenario' => 'create',
104
                'data' => function ($action, $data) {
105
                    foreach ($data['models'] as $model) {
106
                        /** @var Bill $model */
107
                        $model->prepareToCopy();
108
                    }
109
110
                    list($billTypes, $billGroupLabels) = $this->getTypesAndGroups();
111
112
                    return compact('billTypes', 'billGroupLabels');
113
                },
114
            ],
115
            'delete' => [
116
                'class' => SmartPerformAction::class,
117
                'success' => Yii::t('hipanel:finance', 'Payment was deleted successfully'),
118
            ],
119
            'requisites' => [
120
                'class' => RedirectAction::class,
121
                '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...
122
                    $identity = Yii::$app->user->identity;
123
                    $seller = $identity->type === $identity::TYPE_RESELLER ? $identity->username : $identity->seller;
124
                    if ($seller === 'bullet') {
125
                        $seller = 'dsr';
126
                    }
127
128
                    return array_merge(ContactController::getSearchUrl(['client' => $seller]), ['representation' => 'requisites']);
129
                },
130
            ],
131
        ];
132
    }
133
134
    public function actionImport()
135
    {
136
        $model = new BillImportForm([
137
            'billTypes' => array_filter($this->getPaymentTypes(), function ($key) {
138
                // Kick out items that are categories names, but not real types
139
                return strpos($key, ',') !== false;
140
            }, ARRAY_FILTER_USE_KEY),
141
        ]);
142
143
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
144
            $models = $model->parse();
145
146
            if ($models !== false) {
147
                list($billTypes, $billGroupLabels) = $this->getTypesAndGroups();
148
149
                return $this->render('create', [
150
                    'models' => $models,
151
                    'model' => reset($models),
152
                    'billTypes' => $billTypes,
153
                    'billGroupLabels' => $billGroupLabels,
154
                ]);
155
            }
156
        }
157
158
        return $this->render('import', ['model' => $model]);
159
    }
160
161
    public function actionCreateExchange()
162
    {
163
        $model = new CurrencyExchangeForm();
164
165
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
166
            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...
167
                Yii::$app->session->addFlash('success', Yii::t('hipanel:finance', 'Currency was exchanged successfully'));
168
                return $this->redirect(['@bill']);
169
            }
170
        }
171
172
        return $this->render('create-exchange', [
173
            'model' => $model,
174
            'rates' => $this->getExchangeRates()
175
        ]);
176
    }
177
178
    /**
179
     * @return array
180
     */
181
    public function getPaymentTypes()
182
    {
183
        return $this->billTypesProvider->getTypesList();
184
    }
185
186
    /**
187
     * @return array
188
     */
189
    private function getTypesAndGroups()
190
    {
191
        return $this->billTypesProvider->getGroupedList();
192
    }
193
194
    private function getExchangeRates()
195
    {
196
        return Yii::$app->cache->getOrSet(['exchange-rates', Yii::$app->user->id], function () {
197
            return ExchangeRate::find()->select(['from', 'to', 'rate'])->all();
198
        }, 3600);
199
    }
200
}
201