Conditions | 10 |
Paths | 9 |
Total Lines | 50 |
Code Lines | 29 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
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:
If many parameters/temporary variables are present:
1 | <?php |
||
16 | public function buy(Request $request) |
||
17 | { |
||
18 | $item = ShopItem::findOrFail($request->input('item_id')); |
||
19 | $user = Auth::user(); |
||
20 | |||
21 | if ($item->hasUser($user)) { |
||
22 | return back() |
||
23 | ->with('danger', 'You already own this item !'); |
||
24 | } |
||
25 | |||
26 | if ($item->quantity == 0) { |
||
27 | return back() |
||
28 | ->with('danger', 'There\'s no more quantity for this item.'); |
||
29 | } |
||
30 | |||
31 | if (!is_null($item->start_at) && $item->start_at->timestamp >= time()) { |
||
32 | return back() |
||
33 | ->with('danger', 'The sale of the item has not yet beginning.'); |
||
34 | } |
||
35 | |||
36 | if (!is_null($item->end_at) && $item->end_at->timestamp <= time()) { |
||
37 | return back() |
||
38 | ->with('danger', 'The sale of the item has been finished.'); |
||
39 | } |
||
40 | |||
41 | if ($user->rubies_total < $item->price) { |
||
42 | return back() |
||
43 | ->with('danger', 'You don\'t have enough rubies !.'); |
||
44 | } |
||
45 | |||
46 | // Attach the new shop_item to the user. |
||
47 | $result = $user->shopItems()->syncWithoutDetaching($item); |
||
48 | |||
49 | // Decrement user rubies by the price. |
||
50 | $user->decrement('rubies_total', $item->price); |
||
51 | |||
52 | // If the quantity is limited, then decrement the quantity. |
||
53 | if ($item->quantity >= 1) { |
||
54 | $item->quantity--; |
||
55 | $item->save(); |
||
56 | } |
||
57 | |||
58 | if (!empty($result['attached'])) { |
||
59 | $user->notify(new ShopItemNotification($item)); |
||
60 | |||
61 | return back() |
||
62 | ->with('success', 'You have successfully bought the item <b>' . e($item->title) . '</b>'); |
||
63 | } else { |
||
64 | return back() |
||
65 | ->with('danger', 'Can not sync the item to your account !'); |
||
66 | } |
||
69 |