MoneyController::exchangeAction()   F
last analyzed

Complexity

Conditions 19
Paths 1152

Size

Total Lines 47
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 37
nc 1152
nop 0
dl 0
loc 47
rs 2.578
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Money app Controller
5
 *
6
 * @author Alexey Krupskiy <[email protected]>
7
 * @link http://inji.ru/
8
 * @copyright 2015 Alexey Krupskiy
9
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
10
 */
11
class MoneyController extends Controller {
0 ignored issues
show
Bug introduced by
The type Controller was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
13
    public function transferAction() {
14
        $transfer = new Money\Transfer();
15
        $form = new Ui\ActiveForm($transfer, 'transfer');
0 ignored issues
show
Bug introduced by
The type Ui\ActiveForm was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
        $transferId = $form->checkRequest();
17
        if ($transferId) {
18
            $transfer = Money\Transfer::get($transferId);
19
            $transfer->user_id = \Users\User::$cur->id;
0 ignored issues
show
Bug introduced by
The property user_id does not exist on false.
Loading history...
20
            $transfer->code = Tools::randomString();
0 ignored issues
show
Bug introduced by
The type Tools was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The property code does not exist on false.
Loading history...
21
            $transfer->save();
22
23
            $wallets = $this->money->getUserWallets();
24
            $text = 'Перевод средств для ' . $transfer->toUser->name();
0 ignored issues
show
Bug introduced by
The property toUser does not exist on false.
Loading history...
25
            $wallets[$transfer->currency_id]->diff(-$transfer->amount, $text);
0 ignored issues
show
Bug introduced by
The property amount does not exist on false.
Loading history...
Bug introduced by
The property currency_id does not exist on false.
Loading history...
26
            \App::$cur->users->AddUserActivity($transfer->user_id, 4, $text . '<br />' . (float) $transfer->amount . ' ' . $wallets[$transfer->currency_id]->currency->acronym());
27
28
            $block = new Money\Wallet\Block();
29
            $block->wallet_id = $wallets[$transfer->currency_id]->id;
0 ignored issues
show
Bug Best Practice introduced by
The property wallet_id does not exist on Money\Wallet\Block. Since you implemented __set, consider adding a @property annotation.
Loading history...
30
            $block->amount = $transfer->amount;
0 ignored issues
show
Bug Best Practice introduced by
The property amount does not exist on Money\Wallet\Block. Since you implemented __set, consider adding a @property annotation.
Loading history...
31
            $block->comment = 'Заблокированно на перевод средств для ' . $transfer->toUser->name();
0 ignored issues
show
Bug Best Practice introduced by
The property comment does not exist on Money\Wallet\Block. Since you implemented __set, consider adding a @property annotation.
Loading history...
32
            $block->data = 'Money\Transfer:' . $transfer->id;
0 ignored issues
show
Bug Best Practice introduced by
The property data does not exist on Money\Wallet\Block. Since you implemented __set, consider adding a @property annotation.
Loading history...
Bug introduced by
The property id does not exist on false.
Loading history...
33
            $block->save();
34
35
            $from = 'noreply@' . INJI_DOMAIN_NAME;
36
            $to = \Users\User::$cur->mail;
37
            $subject = 'Подтверждение перевода';
38
            $text = 'Чтобы подтвержить перевод №' . $transfer->id . ' введите код <b>' . $transfer->code . '</b> на <a href = "http://' . INJI_DOMAIN_NAME . '/money/confirmTransfer/' . $transfer->id . '?code=' . $transfer->code . '">странице</a> перевода';
39
            Tools::sendMail($from, $to, $subject, $text);
40
            Tools::redirect('/money/confirmTransfer/' . $transfer->id);
41
        }
42
        $this->view->setTitle('Перевод средств');
43
        $this->view->page(['data' => compact('form')]);
44
    }
45
46
    public function confirmTransferAction($transferId = 0) {
47
        $transfer = Money\Transfer::get((int) $transferId);
48
        if (!$transfer || $transfer->user_id != \Users\User::$cur->id || $transfer->complete || $transfer->canceled) {
49
            Tools::redirect('/', 'Такой перевод не найден');
50
        }
51
        if (!empty($_POST['code'])) {
52
            if ($transfer->code != $_POST['code']) {
0 ignored issues
show
Bug introduced by
The property code does not exist on false.
Loading history...
53
                \Inji\Msg::add('Код не совпадает', 'danger');
54
            } else {
55
                $transfer->complete = 1;
0 ignored issues
show
Bug introduced by
The property complete does not exist on false.
Loading history...
56
                $block = Money\Wallet\Block::get('Money\Transfer:' . $transfer->id, 'data');
0 ignored issues
show
Bug introduced by
The property id does not exist on false.
Loading history...
57
                $block->delete();
58
                $wallets = $this->money->getUserWallets($transfer->to_user_id);
0 ignored issues
show
Bug introduced by
The property to_user_id does not exist on false.
Loading history...
59
                $text = 'Перевод средств от ' . $transfer->user->name() . '.' . ($transfer->comment ? ' Комментарий:' . $transfer->comment : '');
0 ignored issues
show
Bug introduced by
The property comment does not exist on false.
Loading history...
Bug introduced by
The property user does not exist on false.
Loading history...
60
                $wallets[$transfer->currency_id]->diff($transfer->amount, $text);
0 ignored issues
show
Bug introduced by
The property currency_id does not exist on false.
Loading history...
Bug introduced by
The property amount does not exist on false.
Loading history...
61
                \App::$cur->users->AddUserActivity($transfer->to_user_id, 4, $text . '<br />' . (float) $transfer->amount . ' ' . $wallets[$transfer->currency_id]->currency->acronym());
62
                $transfer->save();
63
                Tools::redirect('/users/cabinet', 'Перевод был успешно завершен', 'success');
64
            }
65
        }
66
        $this->view->setTitle('Подтверждение перевода средств');
67
        $this->view->page(['data' => compact('transfer')]);
68
    }
69
70
    public function cancelTransferAction($transferId = 0) {
71
        $transfer = Money\Transfer::get((int) $transferId);
72
        if (!$transfer || $transfer->user_id != \Users\User::$cur->id || $transfer->complete || $transfer->canceled) {
73
            Tools::redirect('/', 'Такой перевод не найден');
74
        }
75
        $transfer->cancel();
76
        Tools::redirect('/users/cabinet', 'Перевод был успешно отменен', 'success');
77
    }
78
79
    public function refillAction($currencyId = 0) {
80
        $currency = null;
81
        if (!empty($_POST['currency_id'])) {
82
            $currency = Money\Currency::get((int) $_POST['currency_id']);
83
        }
84
        if ($currency && !empty($_POST['amount'])) {
85
            $pay = new Money\Pay([
86
                'data' => '',
87
                'user_id' => \Users\User::$cur->id,
88
                'currency_id' => $currency->id,
89
                'sum' => (float) str_replace(',', '.', $_POST['amount']),
90
                'type' => 'refill',
91
                'description' => 'Пополнение баланса ' . $currency->name(),
92
                'callback_module' => 'Money',
93
                'callback_method' => 'refillPayRecive'
94
            ]);
95
            $pay->save();
96
            Tools::redirect('/money/merchants/pay/' . $pay->id);
97
        } else {
98
            $currencies = Money\Currency::getList(['where' => ['refill', 1], 'forSelect' => true]);
99
            $this->view->setTitle('Пополнение счета');
100
            $this->view->page(['data' => compact('currencies')]);
101
        }
102
    }
103
104
    public function exchangeAction() {
105
        $wallets = $this->module->getUserWallets();
106
        $currency = !empty($_GET['currency_id']) ? \Money\Currency::get((int) $_GET['currency_id']) : null;
107
        if ($currency && empty($wallets[$currency->id])) {
108
            $currency = null;
109
        }
110
        $targetCurrency = !empty($_GET['target_currency_id']) ? \Money\Currency::get((int) $_GET['target_currency_id']) : null;
111
        if ($targetCurrency && empty($wallets[$targetCurrency->id])) {
112
            $targetCurrency = null;
113
        }
114
        $where = [];
115
        if ($currency) {
116
            $where[] = ['currency_id', $currency->id];
117
        } else {
118
            $where[] = ['currency_id', implode(',', array_keys($wallets)), 'IN'];
119
        }
120
        if ($targetCurrency) {
121
            $where[] = ['target_currency_id', $targetCurrency->id];
122
        } else {
123
            $where[] = ['target_currency_id', implode(',', array_keys($wallets)), 'IN'];
124
        }
125
        if ($where) {
126
            $rates = Money\Currency\ExchangeRate::getList(['where' => $where]);
127
        } else {
128
            $rates = [];
129
        }
130
        if (!empty($_GET['exchange']) && $currency && $targetCurrency && !empty($rates[$_GET['exchange']['rate_id']])) {
131
            $error = false;
132
            $rate = $rates[$_GET['exchange']['rate_id']];
133
            if (empty($_GET['exchange']['give']['amount']) || !(float) $_GET['exchange']['give']['amount']) {
134
                \Inji\Msg::add('Укажите сумму которую вы хотите отдать');
135
                $error = true;
136
            } else {
137
                $amount = (float) $_GET['exchange']['give']['amount'];
138
            }
139
            if (!empty($amount) && $amount > $wallets[$currency->id]->amount) {
140
                \Inji\Msg::add('Вы указали сумму большую чем вам доступно');
141
                $error = true;
142
            }
143
            if (!$error) {
144
                $wallets[$currency->id]->diff(-$amount, 'Обмен валюты на ' . $targetCurrency->name());
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $amount does not seem to be defined for all execution paths leading up to this point.
Loading history...
145
                $wallets[$targetCurrency->id]->diff($amount * $rate->rate, 'Обмне валюты с ' . $currency->name());
146
                Tools::redirect('/users/cabinet', 'Обмен был успешно проведен');
147
            }
148
        }
149
        $this->view->setTitle('Обмен валюты');
150
        $this->view->page(['data' => compact('rates', 'currency', 'targetCurrency', 'wallets')]);
151
    }
152
153
    public function walletPayAction($payId, $walletId) {
154
        $pay = Money\Pay::get((int) $payId);
155
        if (!$pay || $pay->user_id != \Users\User::$cur->id) {
156
            Tools::redirect('/money/merchants/pay/', 'Такой счет не найден');
157
        }
158
        $wallet = Money\Wallet::get((int) $walletId);
159
        if (!$wallet || $wallet->user_id != \Users\User::$cur->id) {
160
            Tools::redirect('/money/merchants/pay/' . $pay->id, 'Такой кошелек не найден');
0 ignored issues
show
Bug introduced by
The property id does not exist on false.
Loading history...
161
        }
162
        if ($pay->currency_id != $wallet->currency_id) {
0 ignored issues
show
Bug introduced by
The property currency_id does not exist on false.
Loading history...
163
            $rate = \Money\Currency\ExchangeRate::get([['currency_id', $wallet->currency_id], ['target_currency_id', $pay->currency_id]]);
164
            if (!$rate) {
165
                Tools::redirect('/money/merchants/pay/' . $pay->id, 'Нет возможности оплатить счет в валюте ' . $pay->currency->name() . ' валютой ' . $wallet->currency->name());
0 ignored issues
show
Bug introduced by
The property currency does not exist on false.
Loading history...
166
            }
167
            $sum = $pay->sum / $rate->rate;
0 ignored issues
show
Bug introduced by
The property sum does not exist on false.
Loading history...
Bug introduced by
The property rate does not exist on false.
Loading history...
168
        } else {
169
            $sum = $pay->sum;
170
        }
171
        if ($sum > $wallet->amount) {
0 ignored issues
show
Bug introduced by
The property amount does not exist on false.
Loading history...
172
            Tools::redirect('/money/merchants/pay/' . $pay->id, 'На вашем счете недостаточно средств', 'danger');
173
        }
174
        $wallet->diff(-$sum, 'Оплата счета №' . $payId);
175
        $statuses = \Money\Pay\Status::getList(['key' => 'code']);
176
        if (!empty($statuses['success'])) {
177
            $pay->pay_status_id = $statuses['success']->id;
0 ignored issues
show
Bug introduced by
The property pay_status_id does not exist on false.
Loading history...
Bug Best Practice introduced by
The property id does not exist on Inji\Model. Since you implemented __get, consider adding a @property annotation.
Loading history...
178
        }
179
        $pay->date_recive = date('Y-m-d H:i:s');
0 ignored issues
show
Bug introduced by
The property date_recive does not exist on false.
Loading history...
180
        $pay->save();
181
        if ($pay->callback_module && $pay->callback_method) {
0 ignored issues
show
Bug introduced by
The property callback_module does not exist on false.
Loading history...
Bug introduced by
The property callback_method does not exist on false.
Loading history...
182
            App::$cur->{$pay->callback_module}->{$pay->callback_method}(['status' => 'success', 'payId' => $pay->id, 'pay' => $pay]);
183
        }
184
        Tools::redirect('/users/cabinet', 'Вы успешно оплатили счет', 'success');
185
    }
186
187
    public function primaryPayAction($payId, $currencyId) {
188
        $pay = Money\Pay::get((int) $payId);
189
        if (!$pay || $pay->user_id != \Users\User::$cur->id) {
190
            Tools::redirect('/money/merchants/pay/', 'Такой счет не найден');
191
        }
192
        $merchant = \Money\MerchantHelper\Primary::getMerchant();
193
        if (!$merchant->active) {
0 ignored issues
show
Bug introduced by
The property active does not exist on false.
Loading history...
194
            Tools::redirect('/money/merchants/pay/' . $pay->id, 'Этот способ оплаты недоступен');
0 ignored issues
show
Bug introduced by
The property id does not exist on false.
Loading history...
195
        }
196
        $allowCurrencies = $merchant->allowCurrencies($pay);
197
        $method = [];
198
        foreach ($allowCurrencies as $allowCurrency) {
199
            if ($allowCurrency['currency']->id == $currencyId) {
200
                $method = $allowCurrency;
201
                break;
202
            }
203
        }
204
        if (!$method) {
205
            Tools::redirect('/', 'Валюта для этого способа оплаты не найдена', 'danger');
206
        }
207
        $className = 'Money\MerchantHelper\\' . $merchant->object_name;
0 ignored issues
show
Bug introduced by
The property object_name does not exist on false.
Loading history...
208
        $sum = $className::getFinalSum($pay, $method);
209
        $this->view->setTitle('Прямая оплата');
210
        $this->view->page(['data' => compact('pay', 'sum', 'method')]);
211
    }
212
213
}
214