Conditions | 11 |
Paths | 8 |
Total Lines | 63 |
Code Lines | 34 |
Lines | 0 |
Ratio | 0 % |
Changes | 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 |
||
33 | public function changeRating(): ?string |
||
34 | { |
||
35 | if (!App::$User->isAuth()) { |
||
36 | throw new ForbiddenException('Auth required'); |
||
37 | } |
||
38 | |||
39 | $this->setJsonHeader(); |
||
40 | |||
41 | // get operation type and target user id |
||
42 | $targetId = (int)$this->request->get('target'); |
||
43 | $type = $this->request->get('type'); |
||
44 | |||
45 | // check type of query |
||
46 | if ($type !== '+' && $type !== '-') { |
||
47 | throw new NativeException('Wrong data'); |
||
48 | } |
||
49 | |||
50 | // check if passed user id is exist |
||
51 | if (!Any::isInt($targetId) || $targetId < 1 || !App::$User->isExist($targetId)) { |
||
52 | throw new NotFoundException('Wrong user info'); |
||
53 | } |
||
54 | |||
55 | $cfg = \Apps\ActiveRecord\App::getConfigs('app', 'Profile'); |
||
56 | // check if rating is enabled for website |
||
57 | if (!(bool)$cfg['rating']) { |
||
58 | throw new NativeException('Rating is disabled'); |
||
59 | } |
||
60 | |||
61 | // get target and sender objects |
||
62 | $target = App::$User->identity($targetId); |
||
63 | $sender = App::$User->identity(); |
||
64 | |||
65 | // disable self-based changes ;) |
||
66 | if ($target->getId() === $sender->getId()) { |
||
67 | throw new ForbiddenException('Self change prevented'); |
||
68 | } |
||
69 | |||
70 | // check delay |
||
71 | $diff = Date::convertToDatetime(time() - $cfg['ratingDelay'], Date::FORMAT_SQL_TIMESTAMP); |
||
72 | |||
73 | $query = ProfileRating::where('target_id', $target->getId()) |
||
74 | ->where('sender_id', $sender->getId()) |
||
75 | ->where('created_at', '>=', $diff) |
||
76 | ->orderBy('id', 'DESC'); |
||
77 | if ($query->count() > 0) { |
||
78 | throw new ForbiddenException('Delay required'); |
||
79 | } |
||
80 | |||
81 | // delay is ok, lets insert a row |
||
82 | $record = new ProfileRating(); |
||
83 | $record->target_id = $target->getId(); |
||
84 | $record->sender_id = $sender->getId(); |
||
85 | $record->type = $type; |
||
86 | $record->save(); |
||
87 | |||
88 | if ($type === '+') { |
||
89 | $target->profile->rating += 1; |
||
90 | } else { |
||
91 | $target->profile->rating -= 1; |
||
92 | } |
||
93 | $target->profile->save(); |
||
94 | |||
95 | return json_encode(['status' => 1, 'data' => 'ok']); |
||
96 | } |
||
98 |