Completed
Push — master ( 1e5eab...6a1cd3 )
by Andrii
10:30
created

BillController::actionImport()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 0
cts 20
cp 0
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
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\SmartDeleteAction;
17
use hipanel\actions\SmartPerformAction;
18
use hipanel\actions\SmartUpdateAction;
19
use hipanel\actions\ValidateFormAction;
20
use hipanel\actions\ViewAction;
21
use hipanel\filters\EasyAccessControl;
22
use hipanel\modules\client\controllers\ContactController;
23
use hipanel\modules\finance\actions\BillManagementAction;
24
use hipanel\modules\finance\forms\BillForm;
25
use hipanel\modules\finance\forms\BillImportForm;
26
use hipanel\modules\finance\forms\CurrencyExchangeForm;
27
use hipanel\modules\finance\models\Bill;
28
use hipanel\modules\finance\models\BillSearch;
29
use hipanel\modules\finance\models\Charge;
30
use hipanel\modules\finance\models\ChargeSearch;
31
use hipanel\modules\finance\models\ExchangeRate;
32
use hipanel\modules\finance\providers\BillTypesProvider;
33
use hiqdev\hiart\ActiveDataProvider;
34
use Yii;
35
use yii\base\Event;
36
use yii\base\Module;
37
use yii\data\ArrayDataProvider;
38
39
class BillController extends \hipanel\base\CrudController
40
{
41
    /**
42
     * @var BillTypesProvider
43
     */
44
    private $billTypesProvider;
45
46
    public function __construct($id, Module $module, BillTypesProvider $billTypesProvider, array $config = [])
47
    {
48
        parent::__construct($id, $module, $config);
49
50
        $this->billTypesProvider = $billTypesProvider;
51
    }
52
53
    public function behaviors()
54
    {
55
        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...
56
            'access-bill' => [
57
                'class' => EasyAccessControl::class,
58
                'actions' => [
59
                    'create,import,copy' => 'bill.create',
60
                    'create-exchange' => 'bill.create',
61
                    'update'    => 'bill.update',
62
                    'delete'    => 'bill.delete',
63
                    '*'         => 'bill.read',
64
                ],
65
            ],
66
        ]);
67
    }
68
69
    public function actions()
70
    {
71
        return array_merge(parent::actions(), [
72
            'index' => [
73
                'class' => IndexAction::class,
74
                '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...
75
                    list($billTypes, $billGroupLabels) = $this->getTypesAndGroups();
76
                    $rates = $this->getExchangeRates();
77
78
                    return compact('billTypes', 'billGroupLabels', 'rates');
79
                },
80
            ],
81
            'view' => [
82
                'class' => ViewAction::class,
83
                'on beforePerform' => function (Event $event) {
84
                    /** @var \hipanel\actions\SearchAction $action */
85
                    $action = $event->sender;
86
                    $dataProvider = $action->getDataProvider();
87
                    $dataProvider->query
88
                        ->joinWith('charges')
89
                        ->andWhere(['with_charges' => true]);
90
                },
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' => SmartDeleteAction::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
                $models = BillForm::createMultipleFromBills($models, 'create');
148
                list($billTypes, $billGroupLabels) = $this->getTypesAndGroups();
149
150
                return $this->render('create', [
151
                    'models' => $models,
152
                    'model' => reset($models),
153
                    'billTypes' => $billTypes,
154
                    'billGroupLabels' => $billGroupLabels,
155
                ]);
156
            }
157
        }
158
159
        return $this->render('import', ['model' => $model]);
160
    }
161
162
    public function actionCreateExchange()
163
    {
164
        $model = new CurrencyExchangeForm();
165
166
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
167
            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...
168
                Yii::$app->session->addFlash('success', Yii::t('hipanel:finance', 'Currency was exchanged successfully'));
169
                return $this->redirect(['@bill']);
170
            }
171
        }
172
173
        return $this->render('create-exchange', [
174
            'model' => $model,
175
            'rates' => $this->getExchangeRates()
176
        ]);
177
    }
178
179
    /**
180
     * @return array
181
     */
182
    public function getPaymentTypes()
183
    {
184
        return $this->billTypesProvider->getTypesList();
185
    }
186
187
    /**
188
     * @return array
189
     */
190
    private function getTypesAndGroups()
191
    {
192
        return $this->billTypesProvider->getGroupedList();
193
    }
194
195
    private function getExchangeRates()
196
    {
197
        return Yii::$app->cache->getOrSet(['exchange-rates', Yii::$app->user->id], function () {
198
            return ExchangeRate::find()->select(['from', 'to', 'rate'])->all();
199
        }, 3600);
200
    }
201
}
202