Test Failed
Branch v5 (12d602)
by Alexey
04:51
created

Money   C

Complexity

Total Complexity 68

Size/Duplication

Total Lines 230
Duplicated Lines 3.04 %

Coupling/Cohesion

Components 2
Dependencies 4

Importance

Changes 0
Metric Value
dl 7
loc 230
rs 5.6756
c 0
b 0
f 0
wmc 68
lcom 2
cbo 4

9 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 5 2
A refillPayRecive() 0 9 3
A goToMerchant() 7 17 3
D reciver() 0 36 12
A getUserBlocks() 0 19 4
D getUserWallets() 0 26 10
A rewardTrigger() 0 10 3
B rewardConditionTrigger() 0 15 5
D reward() 0 73 26

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Money often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Money, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Money module
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 Money extends Module {
12
13
    public $currentMerchant = '';
14
15
    public function init() {
16
        if (!empty($this->config['defaultMerchant'])) {
17
            $this->currentMerchant = $this->config['defaultMerchant'];
18
        }
19
    }
20
21
    public function refillPayRecive($data) {
22
        $wallets = $this->getUserWallets($data['pay']->user_id);
23
        foreach ($wallets as $wallet) {
24
            if ($wallet->currency_id == $data['pay']->currency_id) {
25
                $wallet->diff($data['pay']->sum, 'Пополнение');
26
                break;
27
            }
28
        }
29
    }
30
31
    public function goToMerchant($pay, $merchant, $method, $merchantOptions) {
32
        $objectName = $merchant->object_name;
33
34
        if (is_array($pay)) {
35
            $pay = new Money\Pay($pay);
36
            $pay->save();
37
        }
38 View Code Duplication
        switch ($method['type']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
39
            case 'transfer':
40
                $sum = $pay->sum / $method['transfer']->rate;
41
                break;
42
            default:
43
                $sum = $pay->sum;
44
        }
45
        $className = 'Money\MerchantHelper\\' . $objectName;
46
        return $className::goToMerchant($pay->id, $sum, $method['currency'], $merchantOptions['description'], $merchantOptions['success'], $merchantOptions['false']);
47
    }
48
49
    public function reciver($data, $system, $status, $mr) {
50
        if ($system) {
51
            $merchant = \Money\Merchant::get($system, 'object_name');
52
        } else {
53
            $merchant = false;
54
        }
55
        if ($merchant) {
56
            $this->currentMerchant = $system;
57
        }
58
        $className = 'Money\MerchantHelper\\' . $this->currentMerchant;
59
        $result = $className::reciver($data, $status);
60
        $result['pay'] = null;
61
        if (!empty($result['payId'])) {
62
            $result['pay'] = Money\Pay::get($result['payId']);
63
            $mr->pay_id = $result['payId'];
64
        }
65
        if ($result['pay'] && $result['pay']->pay_status_id == 1) {
66
            $statuses = \Money\Pay\Status::getList(['key' => 'code']);
67
            if (!empty($statuses[$result['status']])) {
68
                $result['pay']->pay_status_id = $statuses[$result['status']]->id;
69
            }
70
            $result['pay']->date_recive = date('Y-m-d H:i:s');
71
            $result['pay']->save();
72
            if ($result['status'] == 'success' && $result['pay']->callback_module && $result['pay']->callback_method) {
73
                App::$cur->{$result['pay']->callback_module}->{$result['pay']->callback_method}($result);
74
            }
75
        }
76
        if (!empty($result['callback'])) {
77
            echo $result['callback'];
78
            $mr->result_callback = $result['callback'];
79
        }
80
        if (!empty($result['status'])) {
81
            $mr->status = $result['status'];
82
        }
83
        $mr->save();
84
    }
85
86
    public function getUserBlocks($userId = null) {
87
        $userId = $userId ? $userId : \Users\User::$cur->id;
88
        $blocked = \Money\Wallet\Block::getList(['where' => [
89
            ['wallet:user_id', $userId],
90
            [
91
                ['date_expired', '0000-00-00 00:00:00'],
92
                ['date_expired', date('Y-m-d H:i:s'), '>', 'OR']
93
            ]
94
        ]]);
95
        $blocks = [];
96
        foreach ($blocked as $block) {
97
            if (empty($blocks[$block->wallet->currency_id])) {
98
                $blocks[$block->wallet->currency_id] = $block->amount;
99
            } else {
100
                $blocks[$block->wallet->currency_id] += $block->amount;
101
            }
102
        }
103
        return $blocks;
104
    }
105
106
    /**
107
     * @param null $userId
108
     * @param bool $walletIdasKey
109
     * @param bool $forSelect
110
     * @param bool $transferOnly
111
     * @return \Money\Wallet[]
112
     */
113
    public function getUserWallets($userId = null, $walletIdasKey = false, $forSelect = false, $transferOnly = false) {
114
        $userId = $userId ? $userId : \Users\User::$cur->id;
115
        if (!$userId) {
116
            return [];
117
        }
118
        $this->getUserBlocks($userId);
119
        $where = [['wallet', 1]];
120
        if ($transferOnly) {
121
            $where[] = ['transfer', 1];
122
        }
123
        $currencies = Money\Currency::getList(['where' => $where]);
124
        $wallets = Money\Wallet::getList(['where' => ['user_id', $userId], 'key' => 'currency_id']);
125
        $result = [];
126
        foreach ($currencies as $currency) {
127
            if (empty($wallets[$currency->id])) {
128
                $wallet = new Money\Wallet();
129
                $wallet->user_id = $userId;
130
                $wallet->currency_id = $currency->id;
131
                $wallet->save();
132
                $result[$walletIdasKey ? $wallet->id : $currency->id] = $forSelect ? $wallet->name() : $wallet;
133
            } else {
134
                $result[$walletIdasKey ? $wallets[$currency->id]->id : $currency->id] = $forSelect ? $wallets[$currency->id]->name() : $wallets[$currency->id];
135
            }
136
        }
137
        return $result;
138
    }
139
140
    public function rewardTrigger($event) {
141
        $triggers = Money\Reward\Trigger::getList(['where' => [['type', 'event'], ['value', $event['eventName']]]]);
142
        foreach ($triggers as $trigger) {
143
            $handlers = $this->getSnippets('rewardTriggerHandler');
144
            if (!empty($handlers[$trigger->handler])) {
145
                $handlers[$trigger->handler]['handler']($event['eventObject'], $trigger);
146
            }
147
        }
148
        return $event['eventObject'];
149
    }
150
151
    public function rewardConditionTrigger($event) {
152
        $items = Money\Reward\Condition\Item::getList(['where' => [['type', 'event'], ['value', $event['eventName']]]]);
153
        foreach ($items as $item) {
154
            $recivers = $this->getSnippets('rewardConditionItemReciver');
155
            if (!empty($recivers[$item->reciver])) {
156
                $recivers[$item->reciver]['reciver']($event['eventObject'], $item);
157
                foreach ($item->condition->rewards as $reward) {
158
                    if ($reward->block) {
159
                        $reward->checkBlocked();
160
                    }
161
                }
162
            }
163
        }
164
        return $event['eventObject'];
165
    }
166
167
    public function reward($reward_id, $sums = [], $rootUser = null) {
168
        $rootUser = $rootUser ? $rootUser : \Users\User::$cur;
169
        $reward = \Money\Reward::get($reward_id);
170
        if (!$reward->active) {
171
            return false;
172
        }
173
        $reward->checkBlocked();
174
        $reward_count = \Money\Reward\Recive::getCount(['where' => ['reward_id', $reward_id]]);
175
        if ($reward_count >= $reward->quantity && $reward->quantity) {
176
            return false;
177
        }
178
        $types = $this->getSnippets('rewardType');
179
        $checkers = $this->getSnippets('userActivity');
180
        foreach ($reward->levels(['order' => ['level', 'asc']]) as $level) {
181
            $user = $rootUser;
182
            for ($i = 0; $i < $level->level; $i++) {
183
                $next = $user && $user->parent ? $user->parent : false;
184
                if (!$next && $reward->lasthaveall) {
185
                    break;
186
                }
187
                $noActive = $next->blocked;
188
                foreach ($checkers as $checker) {
189
                    if ($noActive) {
190
                        break;
191
                    }
192
                    $noActive = !$checker['checker']($next);
193
                }
194
                if ($next && $next->parent_id && $noActive) {
195
                    foreach ($next->users as $childUser) {
196
                        $childUser->parent_id = $next->parent_id;
197
                        $childUser->save();
198
                    }
199
                    $i--;
200
                    $user = Users\User::get($user->id);
201
                    $rootUser = Users\User::get($rootUser->id);
202
                    continue;
203
                }
204
                $user = $next;
205
            }
206
            if (!$user) {
207
                continue;
208
            }
209
210
            if ($reward->peruser) {
211
                $recives = \Money\Reward\Recive::getList(['where' => [['user_id', $user->id], ['reward_id', $reward->id]]]);
212
                $amount = 0;
213
                foreach ($recives as $recive) {
214
                    $amount += $recive->amount;
215
                }
216
                if ($amount >= $reward->peruser) {
217
                    continue;
218
                }
219
            }
220
            $rewardGet = true;
221
            if (!$level->nocondition) {
222
                foreach ($reward->conditions as $condition) {
223
                    if (!$condition->checkComplete($user->id)) {
224
                        $rewardGet = false;
225
                        break;
226
                    }
227
                }
228
                if (!$rewardGet && !$reward->block) {
229
                    continue;
230
                }
231
            }
232
            $recive = new \Money\Reward\Recive();
233
            $recive->reward_id = $reward->id;
234
            $recive->user_id = $user->id;
235
            $recive->amount = 1;
236
            $recive->save();
237
            return $types[$level->type]['rewarder']($reward, $sums, $user, $rootUser, $level, $rewardGet);
238
        }
239
    }
240
}