Completed
Push — master ( 9b654e...e376af )
by Alexey
04:55
created

Money   C

Complexity

Total Complexity 67

Size/Duplication

Total Lines 228
Duplicated Lines 3.07 %

Coupling/Cohesion

Components 2
Dependencies 13

Importance

Changes 4
Bugs 2 Features 0
Metric Value
wmc 67
c 4
b 2
f 0
lcom 2
cbo 13
dl 7
loc 228
rs 5.2808

9 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 6 2
A refillPayRecive() 0 10 3
A goToMerchant() 7 18 3
D reciver() 0 37 12
A getUserBlocks() 0 20 4
D getUserWallets() 0 27 10
A rewardTrigger() 0 10 3
B rewardConditionTrigger() 0 15 5
D reward() 0 71 25

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