Completed
Push — work-fleets ( c7cb6b...1699ac )
by SuperNova.WS
05:47
created

BuddyModel::beFriend()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 6
eloc 17
nc 4
nop 1
dl 0
loc 27
rs 8.439
c 5
b 0
f 0
ccs 0
cts 21
cp 0
crap 42
1
<?php
2
3
namespace Buddy;
4
5
use classSupernova;
6
use db_mysql;
7
use DbEmptyIterator;
8
use DbMysqliResultIterator;
9
use DBStaticMessages;
10
use DBStaticUser;
11
use Entity;
12
13
/**
14
 * Class BuddyModel
15
 *
16
 * @property int|float $playerSenderId Who makes buddy request
17
 * @property int|float $playerOwnerId To whom this buddy request made
18
 * @property int       $buddyStatusId Current buddy request status
19
 * @property string    $requestText Request text
20
 *
21
 * @package Buddy
22
 */
23
class BuddyModel extends Entity {
24
25
  protected static $tableName = 'buddy';
26
  protected static $idField = 'BUDDY_ID';
27
28
  // TODO - make it work with Model's properties
29
  /**
30
   * Property list
31
   *
32
   * @var array
33
   */
34
  protected static $_properties = array(
35
    'dbId'           => array(
36
      P_DB_FIELD => 'BUDDY_ID',
37
    ),
38
    'playerSenderId' => array(
39
      P_DB_FIELD => 'BUDDY_SENDER_ID',
40
    ),
41
    'playerOwnerId'  => array(
42
      P_DB_FIELD => 'BUDDY_OWNER_ID',
43
    ),
44
    'buddyStatusId'  => array(
45
      P_DB_FIELD => 'BUDDY_STATUS',
46
    ),
47
    'requestText'    => array(
48
      P_DB_FIELD => 'BUDDY_REQUEST',
49
    ),
50
  );
51
52
  // TODO - remove public static function db_buddy_update_status($buddy_id, $status) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
41% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
53
  public function db_buddy_update_status($status) {
54
    $buddy_id = idval($this->dbId);
55
56
    doquery("UPDATE `{{buddy}}` SET `BUDDY_STATUS` = {$status} WHERE `BUDDY_ID` = '{$buddy_id}' LIMIT 1;");
57
58
    return classSupernova::$db->db_affected_rows();
59
  }
60
61
  /**
62
   * @param int $playerIdSafe
63
   * @param int $newFriendIdSafe
64
   *
65
   * @throws BuddyException
66
   */
67
  public function db_buddy_check_relation($playerIdSafe, $newFriendIdSafe) {
68
    $result = static::$dbStatic->doQueryFetchValue(
69
      "SELECT `BUDDY_ID` FROM `{{buddy}}` WHERE
70
      (`BUDDY_SENDER_ID` = {$playerIdSafe} AND `BUDDY_OWNER_ID` = {$newFriendIdSafe})
71
      OR
72
      (`BUDDY_SENDER_ID` = {$newFriendIdSafe} AND `BUDDY_OWNER_ID` = {$playerIdSafe})
73
      LIMIT 1 FOR UPDATE;"
74
    );
75
76
    if (!empty($result)) {
77
      throw new BuddyException('buddy_err_adding_exists', ERR_WARNING);
78
    }
79
  }
80
81
  /**
82
   * @param db_mysql $db
83
   * @param mixed    $user_id
84
   *
85
   * @return DbEmptyIterator|DbMysqliResultIterator
86
   */
87
  // TODO - make it non-static
88
  public static function db_buddy_list_by_user($db, $user_id) {
89
    return ($user_id = idval($user_id)) ? $db->doQueryIterator(
90
      "SELECT
91
      b.*,
92
      IF(b.BUDDY_OWNER_ID = {$user_id}, b.BUDDY_SENDER_ID, b.BUDDY_OWNER_ID) AS BUDDY_USER_ID,
93
      u.username AS BUDDY_USER_NAME,
94
      p.name AS BUDDY_PLANET_NAME,
95
      p.galaxy AS BUDDY_PLANET_GALAXY,
96
      p.system AS BUDDY_PLANET_SYSTEM,
97
      p.planet AS BUDDY_PLANET_PLANET,
98
      a.id AS BUDDY_ALLY_ID,
99
      a.ally_name AS BUDDY_ALLY_NAME,
100
      u.onlinetime
101
    FROM {{buddy}} AS b
102
      LEFT JOIN {{users}} AS u ON u.id = IF(b.BUDDY_OWNER_ID = {$user_id}, b.BUDDY_SENDER_ID, b.BUDDY_OWNER_ID)
103
      LEFT JOIN {{planets}} AS p ON p.id_owner = u.id AND p.id = id_planet
104
      LEFT JOIN {{alliance}} AS a ON a.id = u.ally_id
105
    WHERE (`BUDDY_OWNER_ID` = {$user_id}) OR `BUDDY_SENDER_ID` = {$user_id}
106
    ORDER BY BUDDY_STATUS, BUDDY_ID"
107
    ) : new DbEmptyIterator();
108
  }
109
110
  /**
111
   * @param BuddyRoutingParams $cBuddy
112
   *
113
   * @throws BuddyException
114
   */
115
  public function accept($cBuddy) {
116
    if ($cBuddy->mode != 'accept') {
117
      return;
118
    }
119
120
    $playerId = $cBuddy->playerId;
121
122
    if ($this->playerSenderId == $playerId) {
123
      throw new BuddyException('buddy_err_accept_own', ERR_ERROR);
124
    }
125
126
    if ($this->playerOwnerId != $playerId) {
127
      throw new BuddyException('buddy_err_accept_alien', ERR_ERROR);
128
    }
129
130
    if ($this->buddyStatusId == BUDDY_REQUEST_ACTIVE) {
131
      throw new BuddyException('buddy_err_accept_already', ERR_WARNING);
132
    }
133
134
    if ($this->buddyStatusId == BUDDY_REQUEST_DENIED) {
135
      throw new BuddyException('buddy_err_accept_denied', ERR_ERROR);
136
    }
137
138
    if ($this->buddyStatusId != BUDDY_REQUEST_WAITING) {
139
      throw new BuddyException('buddy_err_unknown_status', ERR_ERROR);
140
    }
141
142
    $result = $this->db_buddy_update_status(BUDDY_REQUEST_ACTIVE);
143
    if ($result) {
144
      DBStaticMessages::msgSendFromPlayerBuddy($cBuddy, 'buddy_msg_accept_title', 'buddy_msg_accept_text');
145
      throw new BuddyException('buddy_err_accept_none', ERR_NONE);
146
    } else {
147
      throw new BuddyException('buddy_err_accept_internal', ERR_ERROR);
148
    }
149
  }
150
151
  /**
152
   * Declining buddy request
153
   *
154
   * If it is own request - it will be deleted
155
   *
156
   * @param BuddyRoutingParams $cBuddy
157
   *
158
   * @throws BuddyException
159
   */
160
  public function decline($cBuddy) {
161
    if ($cBuddy->mode != 'delete') {
162
      return;
163
    }
164
165
    $playerId = $cBuddy->playerId;
166
167
    if ($this->playerSenderId != $playerId && $this->playerOwnerId != $playerId) {
168
      throw new BuddyException('buddy_err_delete_alien', ERR_ERROR);
169
    }
170
171
    if ($this->buddyStatusId == BUDDY_REQUEST_ACTIVE) {
172
      // Existing friendship
173
      $ex_friend_id = $this->playerSenderId == $playerId ? $this->playerOwnerId : $this->playerSenderId;
0 ignored issues
show
Unused Code introduced by
$ex_friend_id 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...
174
175
      DBStaticMessages::msgSendFromPlayerBuddy($cBuddy, 'buddy_msg_unfriend_title', 'buddy_msg_unfriend_text');
176
177
      static::$rowOperator->deleteById($this);
178
      throw new BuddyException('buddy_err_unfriend_none', ERR_NONE);
179
    } elseif ($this->playerSenderId == $playerId) {
180
      // Player's outcoming request - either denied or waiting
181
      static::$rowOperator->deleteById($this);
182
      throw new BuddyException('buddy_err_delete_own', ERR_NONE);
183
    } elseif ($this->buddyStatusId == BUDDY_REQUEST_WAITING) {
184
      // Deny incoming request
185
      DBStaticMessages::msgSendFromPlayerBuddy($cBuddy, 'buddy_msg_deny_title', 'buddy_msg_deny_text');
186
187
      $this->db_buddy_update_status(BUDDY_REQUEST_DENIED);
188
      throw new BuddyException('buddy_err_deny_none', ERR_NONE);
189
    }
190
  }
191
192
  /**
193
   * @param int    $newFriendIdSafe
194
   * @param string $newFriendNameUnsafe
195
   *
196
   * @return array|bool|false|\mysqli_result|null
197
   */
198
  protected function getNewFriend($newFriendIdSafe, $newFriendNameUnsafe) {
199
    $new_friend_row = array();
200
    if ($newFriendIdSafe) {
201
      $new_friend_row = DBStaticUser::db_user_by_id($newFriendIdSafe, true, '`id`, `username`');
202
    } elseif ($newFriendNameUnsafe) {
203
      $new_friend_row = DBStaticUser::db_user_by_username($newFriendNameUnsafe, true, '`id`, `username`');
204
    }
205
206
    return $new_friend_row;
207
  }
208
209
  /**
210
   * @param BuddyRoutingParams $cBuddy
211
   *
212
   * @throws BuddyException
213
   */
214
  public function beFriend($cBuddy) {
215
    if (empty($cBuddy->newFriendIdSafe) && empty($cBuddy->new_friend_name_unsafe)) {
216
      return;
217
    }
218
219
    $new_friend_row = $this->getNewFriend($cBuddy->newFriendIdSafe, $cBuddy->new_friend_name_unsafe);
220
221
    if (empty($new_friend_row) || empty($new_friend_row['id'])) {
222
      throw new BuddyException('buddy_err_unknown_player', ERR_ERROR);
223
    }
224
225
    if ($new_friend_row['id'] == $cBuddy->playerId) {
226
      throw new BuddyException('buddy_err_adding_self', ERR_ERROR);
227
    }
228
229
    $cBuddy->newFriendIdSafe = $new_friend_row['id'];
230
    $this->db_buddy_check_relation($cBuddy->playerId, $new_friend_row['id']);
0 ignored issues
show
Bug introduced by
It seems like $cBuddy->playerId can also be of type double or object<Closure>; however, Buddy\BuddyModel::db_buddy_check_relation() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
231
    DBStaticMessages::msgSendFromPlayerBuddy($cBuddy, 'buddy_msg_adding_title', 'buddy_msg_adding_text');
232
233
    $this->playerSenderId = idval($cBuddy->playerId);
234
    $this->playerOwnerId = idval($new_friend_row['id']);
235
    $this->buddyStatusId = BUDDY_REQUEST_WAITING;
236
    $this->requestText = $cBuddy->new_request_text_unsafe;
237
238
    static::$rowOperator->insert($this);
239
    throw new BuddyException('buddy_err_adding_none', ERR_NONE);
240
  }
241
242
  public function isContainerEmpty() {
243
    return
244
      $this->buddyStatusId == null
245
      ||
246
      $this->buddyStatusId == BUDDY_REQUEST_NOT_SET
247
      ||
248
      empty($this->playerSenderId)
249
      ||
250
      empty($this->playerOwnerId);
251
  }
252
253
  /**
254
   * Trying to load object info by buddy ID - if it is supplied
255
   *
256
   * @param BuddyRoutingParams $cBuddy
257
   *
258
   * @throws BuddyException
259
   */
260
  protected function loadTry($cBuddy) {
261
    if ($cBuddy->buddy_id) {
262
      $this->dbId = $cBuddy->buddy_id;
263
      static::$rowOperator->getById($this);
264
265
      if ($this->isContainerEmpty()) {
266
        throw new BuddyException('buddy_err_not_exist', ERR_ERROR);
267
      }
268
    }
269
  }
270
271
  /**
272
   * @param BuddyRoutingParams $cBuddy
273
   *
274
   * @throws BuddyException
275
   */
276
  public function route($cBuddy) {
277
    // Trying to load buddy record with supplied dbId
278
    $this->loadTry($cBuddy);
279
    // Trying to accept buddy request
280
    $this->accept($cBuddy);
281
    // Trying to decline buddy request. If it's own request - it will be deleted
282
    $this->decline($cBuddy);
283
    // New request?
284
    $this->beFriend($cBuddy);
285
  }
286
287
}
288