Completed
Push — work-fleets ( 77ad6e...489db6 )
by SuperNova.WS
06:17
created

DBStaticUser::db_user_by_username()   D

Complexity

Conditions 18
Paths 13

Size

Total Lines 37
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 342

Importance

Changes 5
Bugs 1 Features 0
Metric Value
cc 18
eloc 19
c 5
b 1
f 0
nc 13
nop 5
dl 0
loc 37
rs 4.947
ccs 0
cts 28
cp 0
crap 342

How to fix   Complexity   

Long Method

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:

1
<?php
2
3
/**
4
 * Class DBStaticUser
5
 */
6
class DBStaticUser extends DBStaticRecord {
7
8
  public static $_table = 'users';
9
  public static $_idField = 'id';
10
11
  protected static function whereNotAlly() {
12
13
  }
14
15
  // TODO - это вообще-то надо хранить в конфигурации
16
  /**
17
   * @return string
18
   */
19
  public static function getLastRegisteredUserName() {
20
    $query =
21
      static::buildDBQ()
22
        ->field('username')
23
        ->where('`user_as_ally` IS NULL')
0 ignored issues
show
Documentation introduced by
'`user_as_ally` IS NULL' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
24
        ->orderBy(array('`id` DESC'));
25
26
    return (string)$query->selectValue();
27
  }
28
29
  /**
30
   * @return DbResultIterator
31
   */
32
  public static function db_player_list_export_blitz_info() {
33
    return
34
      static::buildDBQ()
35
        ->fields(array('id', 'username', 'total_rank', 'total_points', 'onlinetime',))
36
        ->where('`user_as_ally` IS NULL')
0 ignored issues
show
Documentation introduced by
'`user_as_ally` IS NULL' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
37
        ->orderBy(array('`id`'))
38
        ->selectIterator();
39
  }
40
41
  /**
42
   * @return DbResultIterator
43
   */
44
  public static function db_user_list_non_bots() {
45
//    $query = doquery("SELECT `id` FROM {{users}} WHERE `user_as_ally` IS NULL AND `user_bot` = " . USER_BOT_PLAYER . " FOR UPDATE;");
46
47
    $query =
48
      static::buildDBQ()
49
        ->field('id')
50
        ->where("`user_as_ally` IS NULL")
0 ignored issues
show
Documentation introduced by
'`user_as_ally` IS NULL' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
51
        ->where("`user_bot` = " . USER_BOT_PLAYER)
0 ignored issues
show
Documentation introduced by
'`user_bot` = ' . USER_BOT_PLAYER is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
52
        ->setForUpdate();
53
54
    return $query->selectIterator();
55
  }
56
57
  public static function db_user_lock_with_target_owner_and_acs($user, $planet = array()) {
58
    $query = "SELECT 1 FROM `{{users}}` WHERE `id` = " . idval($user['id']) .
59
      (!empty($planet['id_owner']) ? ' OR `id` = ' . idval($planet['id_owner']) : '')
60
      . " FOR UPDATE";
61
62
    static::getDb()->doSelect($query);
63
  }
64
65
  /**
66
   * @param bool $online
67
   *
68
   * @return int
69
   */
70
  public static function db_user_count($online = false) {
71
    return intval(static::getDb()->doSelectFetchValue(
72
      "SELECT COUNT(`id`) AS `user_count` 
73
      FROM `{{users}}` 
74
      WHERE 
75
        `user_as_ally` IS NULL" .
76
        ($online ? ' AND `onlinetime` > ' . (SN_TIME_NOW - classSupernova::$config->game_users_online_timeout) : '')
0 ignored issues
show
Documentation introduced by
The property game_users_online_timeout does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
77
    ));
78
  }
79
80
  public static function db_user_list_admin_sorted($sort, $online = false) {
81
//    $query = "SELECT
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
82
//          u.*, COUNT(r.id) AS referral_count, SUM(r.dark_matter) AS referral_dm
83
//      FROM
84
//          {{users}} as u
85
//          LEFT JOIN
86
//              {{referrals}} as r on r.id_partner = u.id
87
//      WHERE " .
88
//      ($online ? "`onlinetime` >= :onlineTime" : 'user_as_ally IS NULL') .
89
//      " GROUP BY u.id
90
//        ORDER BY user_as_ally, {$sort} ASC";
91
92
    $query = static::buildDBQ()
93
      ->setAlias('u')
94
      ->field('u.*')
95
      ->fieldCount('r.id', 'referral_count')
96
      ->fieldSingleFunction('sum', 'r.dark_matter', 'referral_dm')
97
      ->join('LEFT JOIN {{referrals}} as r on r.id_partner = u.id')
98
      ->where($online ? "`onlinetime` >= " . intval(SN_TIME_NOW - classSupernova::$config->game_users_online_timeout) : 'user_as_ally IS NULL')
0 ignored issues
show
Documentation introduced by
The property game_users_online_timeout does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Documentation introduced by
$online ? '`onlinetime` ... 'user_as_ally IS NULL' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
99
      ->groupBy('u.id')
0 ignored issues
show
Documentation introduced by
'u.id' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
100
      ->orderBy("user_as_ally, {$sort} ASC");
101
102
    $result = $query->selectIterator();
103
104
    return $result;
105
  }
106
107
  public static function db_user_list_to_celebrate($config_user_birthday_range) {
108
    $query = static::buildDBQ()
109
      ->field('id', 'username', 'user_birthday', 'user_birthday_celebrated')
110
      ->fieldLiteral('CONCAT(YEAR(CURRENT_DATE), DATE_FORMAT(`user_birthday`, \'-%m-%d\')) AS `current_birthday`')
111
      ->fieldLiteral('DATEDIFF(CURRENT_DATE, CONCAT(YEAR(CURRENT_DATE), DATE_FORMAT(`user_birthday`, \'-%m-%d\'))) AS `days_after_birthday`')
112
      ->where('`user_birthday` IS NOT NULL')
0 ignored issues
show
Documentation introduced by
'`user_birthday` IS NOT NULL' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
113
      ->where('(`user_birthday_celebrated` IS NULL OR DATE_ADD(`user_birthday_celebrated`, INTERVAL 1 YEAR) < CURRENT_DATE)')
0 ignored issues
show
Documentation introduced by
'(`user_birthday_celebra... YEAR) < CURRENT_DATE)' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
114
      ->where('`user_as_ally` IS NULL')
0 ignored issues
show
Documentation introduced by
'`user_as_ally` IS NULL' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
115
      ->having('`days_after_birthday` >= 0')
116
      ->having('`days_after_birthday` < ' . intval($config_user_birthday_range))
117
      ->setForUpdate();
118
119
    $result = $query->selectIterator();
120
//
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% 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...
121
//    $query = "SELECT
122
//        `id`, `username`, `user_birthday`, `user_birthday_celebrated`,
123
//        CONCAT(YEAR(CURRENT_DATE), DATE_FORMAT(`user_birthday`, '-%m-%d')) AS `current_birthday`,
124
//        DATEDIFF(CURRENT_DATE, CONCAT(YEAR(CURRENT_DATE), DATE_FORMAT(`user_birthday`, '-%m-%d'))) AS `days_after_birthday`
125
//      FROM
126
//        `{{users}}`
127
//      WHERE
128
//        `user_birthday` IS NOT NULL
129
//        AND `user_as_ally` IS NULL
130
//        AND (`user_birthday_celebrated` IS NULL OR DATE_ADD(`user_birthday_celebrated`, INTERVAL 1 YEAR) < CURRENT_DATE)
131
//      HAVING
132
//        `days_after_birthday` >= 0 AND `days_after_birthday` < {$config_user_birthday_range} FOR UPDATE";
133
//
134
//    $result = static::$dbStatic->doQueryIterator($query);
135
136
    return $result;
137
  }
138
139
  /**
140
   * @return DbEmptyIterator|DbMysqliResultIterator
141
   */
142
  public static function db_user_list_admin_multiaccounts() {
143
    $query = "SELECT COUNT(*) AS `ip_count`, `user_lastip`
144
      FROM `{{users}}`
145
      WHERE `user_as_ally` IS NULL
146
      GROUP BY `user_lastip`
147
      HAVING COUNT(*) > 1";
148
149
    return static::getDb()->doSelectIterator($query);
150
  }
151
152
  public static function db_player_list_blitz_delete_players() {
153
    classSupernova::$db->doDelete("DELETE FROM `{{users}}` WHERE `username` LIKE 'Игрок%';");
154
  }
155
156
  public static function db_player_list_blitz_set_50k_dm() {
157
    classSupernova::$db->doUpdate('UPDATE `{{users}}` SET `dark_matter` = 50000, `dark_matter_total` = 50000;');
158
  }
159
160
161
  /**
162
   * Выбирает записи игроков по списку их ID
163
   *
164
   * @param $user_id_list
165
   *
166
   * @return array
167
   */
168
  public static function db_user_list_by_id($user_id_list) {
169
    !is_array($user_id_list) ? $user_id_list = array($user_id_list) : false;
170
171
    $user_list = array();
172
    foreach ($user_id_list as $user_id_unsafe) {
173
      $user = DBStaticUser::db_user_by_id($user_id_unsafe);
174
      !empty($user) ? $user_list[$user_id_unsafe] = $user : false;
175
    }
176
177
    return $user_list;
178
  }
179
180
181
  public static function db_user_by_username($username_unsafe, $for_update = false, $fields = '*', $player = null, $like = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $for_update is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $fields is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
182
    // TODO Проверить, кстати - а везде ли нужно выбирать юзеров или где-то все-таки ищутся Альянсы ?
183
    if (!($username_unsafe = trim($username_unsafe))) {
184
      return false;
185
    }
186
187
    $user = null;
188
    if (SnCache::isArrayLocation(LOC_USER)) {
189
      foreach (SnCache::getData(LOC_USER) as $user_id => $user_data) {
190
        if (is_array($user_data) && isset($user_data['username'])) {
191
          // проверяем поле
192
          // TODO Возможно есть смысл всегда искать по strtolower - но может игрок захочет переименоваться с другим регистром? Проверить!
193
          if ((!$like && $user_data['username'] == $username_unsafe) || ($like && strtolower($user_data['username']) == strtolower($username_unsafe))) {
194
            // $user_as_ally = intval($user_data['user_as_ally']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% 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...
195
            $user_as_ally = idval($user_data['user_as_ally']);
196
            if ($player === null || ($player === true && !$user_as_ally) || ($player === false && $user_as_ally)) {
197
              $user = $user_data;
198
              break;
199
            }
200
          }
201
        }
202
      }
203
    }
204
205
    if ($user === null) {
206
      // Вытаскиваем запись
207
      $username_safe = db_escape($like ? strtolower($username_unsafe) : $username_unsafe); // тут на самом деле strtolower() лишняя, но пусть будет
208
209
      $user = classSupernova::$db->doSelectFetch(
210
        "SELECT * FROM {{users}} WHERE `username` " . ($like ? 'LIKE' : '=') . " '{$username_safe}'"
211
        . " FOR UPDATE"
212
      );
213
      SnCache::cache_set(LOC_USER, $user); // В кэш-юзер так же заполнять индексы
214
    }
215
216
    return $user;
217
  }
218
219
  public static function db_user_list($user_filter = '', $for_update = false, $fields = '*') {
0 ignored issues
show
Unused Code introduced by
The parameter $for_update is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $fields is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
220
    return classSupernova::db_get_record_list(LOC_USER, $user_filter);
221
  }
222
223
  public static function db_user_set_by_id($user_id, $set) {
224
    return classSupernova::db_upd_record_by_id(LOC_USER, $user_id, $set);
225
  }
226
227
  /**
228
   * Возвращает информацию о пользователе по его ID
229
   *
230
   * @param int|array $user_id_unsafe
231
   *    <p>int - ID пользователя</p>
232
   *    <p>array - запись пользователя с установленным полем ['id']</p>
233
   * @param bool      $for_update @deprecated
234
   * @param string    $fields @deprecated список полей или '*'/'' для всех полей
235
   * @param null      $player
236
   * @param bool|null $player Признак выбора записи пользователь типа "игрок"
237
   *    <p>null - Можно выбрать запись любого типа</p>
238
   *    <p>true - Выбирается только запись типа "игрок"</p>
239
   *    <p>false - Выбирается только запись типа "альянс"</p>
240
   *
241
   * @return array|false
242
   *    <p>false - Нет записи с указанным ID и $player</p>
243
   *    <p>array - запись типа $user</p>
244
   */
245
  public static function db_user_by_id($user_id_unsafe, $for_update = false, $fields = '*', $player = null) {
246
    $user = classSupernova::db_get_record_by_id(LOC_USER, $user_id_unsafe, $for_update, $fields);
247
248
    return (is_array($user) &&
249
      (
250
        $player === null
251
        ||
252
        ($player === true && !$user['user_as_ally'])
253
        ||
254
        ($player === false && $user['user_as_ally'])
255
      )) ? $user : false;
256
  }
257
258
259
  public static function db_user_list_set_mass_mail(&$owners_list, $set) {
260
    return classSupernova::db_upd_record_list(LOC_USER, $set, !empty($owners_list) ? '`id` IN (' . implode(',', $owners_list) . ');' : '');
261
  }
262
263
  public static function db_user_list_set_by_ally_and_rank($ally_id, $ally_rank_id, $set) {
264
    return classSupernova::db_upd_record_list(LOC_USER, $set, "`ally_id`={$ally_id} AND `ally_rank_id` >= {$ally_rank_id}");
265
  }
266
267
  public static function db_user_list_set_ally_deprecated_convert_ranks($ally_id, $i, $rank_id) {
268
    return classSupernova::db_upd_record_list(LOC_USER, "`ally_rank_id` = {$i}", "`ally_id` = {$ally_id} AND `ally_rank_id`={$rank_id}");
269
  }
270
271
  /**
272
   * @param array $playerArray
273
   */
274
  public static function renderNameAndCoordinates($playerArray) {
275
    return "{$playerArray['username']} " . uni_render_coordinates($playerArray);
276
  }
277
278
  /**
279
   * @param mixed $user
280
   */
281
  public static function validateUserRecord($user) {
282
    if (!is_array($user)) {
283
      // TODO - remove later
284
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER is not ARRAY</h1>');
285
      pdump(debug_backtrace());
286
      die('USER is not ARRAY');
287
    }
288
    if (!isset($user['id']) || !$user['id']) {
289
      // TODO - remove later
290
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER[id] пустой</h1>');
291
      pdump($user);
292
      pdump(debug_backtrace());
293
      die('USER[id] пустой');
294
    }
295
  }
296
297
  /**
298
   * @param array $playerRowFieldChanges - array of $resourceId => $amount
299
   * @param int   $userId
300
   */
301 View Code Duplication
  public static function db_user_update_resources($playerRowFieldChanges, $userId) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
302
    foreach ($playerRowFieldChanges as $resourceId => &$value) {
303
      $fieldName = pname_resource_name($resourceId);
304
      $value = "{$fieldName} = {$fieldName} + ('{$value}')";
305
    }
306
    if($query = implode(',', $playerRowFieldChanges)) {
307
      classSupernova::$gc->db->doUpdate("UPDATE `{{users}}` SET {$query} WHERE id = {$userId}");
0 ignored issues
show
Bug introduced by
The method doUpdate does only exist in db_mysql, but not in Closure.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
308
    }
309
  }
310
311
}
312