Test Failed
Branch trunk (412648)
by SuperNova.WS
03:40
created

classSupernova::services()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
use Vector\Vector;
4
use Common\GlobalContainer;
5
6
/**
7
 * Class classSupernova
8
 *
9
 * Singleton
10
 */
11
class classSupernova {
12
  /**
13
   * @var classSupernova $_sn
14
   */
15
  protected static $_sn;
16
17
  /**
18
   * @var GlobalContainer $gc
19
   */
20
  public static $gc;
21
22
  /**
23
   * Основная БД для доступа к данным
24
   *
25
   * @var db_mysql $db
26
   */
27
  public static $db;
28
  public static $db_name = '';
29
30
  /**
31
   * Настройки из файла конфигурации
32
   *
33
   * @var string
34
   */
35
  public static $cache_prefix = 'sn_';
36
  // public static $db_prefix = '';
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% 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...
37
  public static $sn_secret_word = '';
38
39
  /**
40
   * Конфигурация игры
41
   *
42
   * @var classConfig $config
43
   */
44
  public static $config;
45
46
47
  /**
48
   * Кэш игры
49
   *
50
   * @var classCache $cache
51
   */
52
  public static $cache;
53
54
55
  /**
56
   * @var core_auth $auth
57
   */
58
  public static $auth = null;
59
60
61
  public static $db_in_transaction = false;
62
  public static $transaction_id = 0;
63
  public static $user = array();
64
  /**
65
   * @var userOptions
66
   */
67
  public static $user_options;
68
69
  /**
70
   * @var debug $debug
71
   */
72
  public static $debug = null;
73
74
75
  public static $options = array();
76
77
78
  /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% 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...
79
  // protected static $user = null;
80
  // protected static $planet = null;
81
  // protected static $ally = null;
82
  */
83
84
  public static $data = array(); // Кэш данных - юзера, планеты, юниты, очередь, альянсы итд
85
  public static $locks = array(); // Информация о блокировках
86
  public static $queries = array(); // Кэш запросов
87
88
  // Массив $locator - хранит отношения между записями для быстрого доступа по тип_записи:тип_локации:ид_локации:внутренний_ид_записи=>информация
89
  // Для LOC_UNIT внутренний ИД - это SNID, а информация - это ссылка на запись `unit`
90
  // Для LOC_QUE внутренний ИД - это тип очереди, а информация - массив ссылок на `que`
91
  public static $locator = array(); // Кэширует соответствия между расположением объектов - в частности юнитов и очередей
92
93
  /**
94
   * Is header already rendered?
95
   *
96
   * @var bool $headerRendered
97
   */
98
  public static $headerRendered = false;
99
100
  // Кэш индексов - ключ MD5-строка от суммы ключевых строк через | - менять | на что-то другое перед поиском и назад - после поиска
101
  // Так же в индексах могут быть двойные вхождения - например, названия планет да и вообще
102
  // Придумать спецсимвол для NULL
103
  // protected static $indexes = array();
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
104
105
  /*
106
  TODO Кэш:
107
  1. Всегда дешевле использовать процессор, чем локальную память
108
  2. Всегда дешевле использовать локальную память, чем общую память всех процессов
109
  3. Всегда дешевле использовать общую память всех процессов, чем обращаться к БД
110
111
  Кэш - многоуровневый: локальная память-общая память-БД
112
  БД может быть сверхкэширующей - см. HyperNova. Это реализуется на уровне СН-драйвера БД
113
  Предусмотреть вариант, когда уровни кэширования совпадают, например когда нет xcache и используется общая память
114
  */
115
  //public static $cache; // Объект-кэшер - либо встроенная память, либо мемкэш с блокировками - находится внутри $db!!!!
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
116
  //public static $db; // Объект-БД - либок кэшер с блокировками, либо БД
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
117
118
  // protected static $info = array(); // Кэш информации - инфо о юнитах, инфо о группах итд
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
119
120
  // TODO Автоматически заполнять эту таблицу. В случае кэша в памяти - делать show table при обращении к таблице
121
  public static $location_info = array(
122
    LOC_USER => array(
123
      P_TABLE_NAME => 'users',
124
      P_ID => 'id',
125
      P_OWNER_INFO => array(),
126
    ),
127
128
    LOC_PLANET => array(
129
      P_TABLE_NAME => 'planets',
130
      P_ID => 'id',
131
      P_OWNER_INFO => array(
132
        LOC_USER => array(
133
          P_LOCATION => LOC_USER,
134
          P_OWNER_FIELD => 'id_owner',
135
        ),
136
      ),
137
    ),
138
139
    LOC_UNIT => array(
140
      P_TABLE_NAME => 'unit',
141
      P_ID => 'unit_id',
142
      P_OWNER_INFO => array(
143
        LOC_USER => array(
144
          P_LOCATION => LOC_USER,
145
          P_OWNER_FIELD => 'unit_player_id',
146
        ),
147
      ),
148
    ),
149
150
    LOC_QUE => array(
151
      P_TABLE_NAME => 'que',
152
      P_ID => 'que_id',
153
      P_OWNER_INFO => array(
154
        array(
155
          P_LOCATION => LOC_USER,
156
          P_OWNER_FIELD => 'que_player_id',
157
        ),
158
159
        array(
160
          P_LOCATION => LOC_PLANET,
161
          P_OWNER_FIELD => 'que_planet_id_origin',
162
        ),
163
164
        array(
165
          P_LOCATION => LOC_PLANET,
166
          P_OWNER_FIELD => 'que_planet_id',
167
        ),
168
      ),
169
    ),
170
171
    LOC_FLEET => array(
172
      P_TABLE_NAME => 'fleets',
173
      P_ID => 'fleet_id',
174
      P_OWNER_INFO => array(
175
        array(
176
          P_LOCATION => LOC_USER,
177
          P_OWNER_FIELD => 'fleet_owner',
178
        ),
179
180
        array(
181
          P_LOCATION => LOC_USER,
182
          P_OWNER_FIELD => 'fleet_target_owner',
183
        ),
184
185
        array(
186
          P_LOCATION => LOC_PLANET,
187
          P_OWNER_FIELD => 'fleet_start_planet_id',
188
        ),
189
190
        array(
191
          P_LOCATION => LOC_PLANET,
192
          P_OWNER_FIELD => 'fleet_end_planet_id',
193
        ),
194
      ),
195
    ),
196
  );
197
198
  /**
199
   * @return classSupernova
200
   */
201
  public static function sn() {
202
    if(!isset(self::$_sn)) {
203
      self::$_sn = new self();
204
    }
205
206
    return self::$_sn;
207
  }
208
209
  public function __construct() {
210
211
  }
212
213
214
  public static function log_file($message, $spaces = 0) {
215
    if(self::$debug) {
216
      self::$debug->log_file($message, $spaces);
217
    }
218
  }
219
220
  // Перепаковывает массив на заданную глубину, убирая поля с null
221 View Code Duplication
  public static function array_repack(&$array, $level = 0) {
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...
222
    // TODO $lock_table не нужна тут
223
    if(!is_array($array)) return;
224
225
    foreach($array as $key => &$value) {
226
      if($value === null) {
227
        unset($array[$key]);
228
      } elseif($level > 0 && is_array($value)) {
229
        static::array_repack($value, $level - 1);
230
        if(empty($value)) unset($array[$key]);
231
      }
232
    }
233
  }
234
235
236
  // TODO Вынести в отдельный объект
237
  public static function cache_repack($location_type, $record_id = 0) {
238
    // Если есть $user_id - проверяем, а надо ли перепаковывать?
239
    if($record_id && isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null) return;
240
241
    static::array_repack(static::$data[$location_type]);
242
    static::array_repack(static::$locator[$location_type], 3); // TODO У каждого типа локации - своя глубина!!!! Но можно и глубже ???
243
    static::array_repack(static::$queries[$location_type], 1);
244
  }
245
  public static function cache_clear($location_type, $hard = true) {
246
    //print("<br />CACHE CLEAR {$cache_id} " . ($hard ? 'HARD' : 'SOFT') . "<br />");
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% 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...
247
    if($hard && !empty(static::$data[$location_type])) {
248
      // Здесь нельзя делать unset - надо записывать NULL, что бы это отразилось на зависимых записях
249
      array_walk(static::$data[$location_type], function(&$item){$item = null;});
250
    }
251
    static::$locator[$location_type] = array();
252
    static::$queries[$location_type] = array();
253
    static::cache_repack($location_type); // Перепаковываем внутренние структуры, если нужно
254
  }
255
  public static function cache_clear_all($hard = true) {
256
    //print('<br />CACHE CLEAR ALL<br />');
257
    if($hard) {
258
      static::$data = array();
259
      static::cache_lock_unset_all();
260
    }
261
    static::$locator = array();
262
    static::$queries = array();
263
  }
264
265
  public static function cache_get($location_type, $record_id) {
266
    return isset(static::$data[$location_type][$record_id]) ? static::$data[$location_type][$record_id] : null;
267
  }
268
  public static function cache_isset($location_type, $record_id) {
269
    return isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null;
270
  }
271
  /* Кэшируем запись в соответствующий кэш
272
273
  Писать в кэш:
274
  1. Если записи не существует в кэше
275
  2. Если стоит $force_overwrite
276
  3. Если во время транзакции существующая запись не заблокирована
277
278
  Блокировать запись:
279
  1. Если идет транзакция и запись не заблокирована
280
  2. Если не стоит скип-лок
281
  */
282
  public static function cache_set($location_type, $record_id, $record, $force_overwrite = false, $skip_lock = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $record_id 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...
283
    // нет идентификатора - выход
284
    if(!($record_id = $record[static::$location_info[$location_type][P_ID]])) return;
285
286
    $in_transaction = static::db_transaction_check(false);
287
    if(
288
      $force_overwrite
289
      ||
290
      // Не заменяются заблокированные записи во время транзакции
291
      ($in_transaction && !static::cache_lock_get($location_type, $record_id))
292
      ||
293
      // !isset(static::$data[$location_type][$record_id]) || static::$data[$location_type][$record_id] === null
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% 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...
294
      !static::cache_isset($location_type, $record_id)
295
    ) {
296
      static::$data[$location_type][$record_id] = $record;
297
      if($in_transaction && !$skip_lock) {
298
        static::cache_lock_set($location_type, $record_id);
299
      }
300
    }
301
  }
302
  public static function cache_unset($cache_id, $safe_record_id) {
303
    // $record_id должен быть проверен заранее !
304
    if(isset(static::$data[$cache_id][$safe_record_id]) && static::$data[$cache_id][$safe_record_id] !== null) {
305
      // Выставляем запись в null
306
      static::$data[$cache_id][$safe_record_id] = null;
307
      // Очищаем кэш мягко - что бы удалить очистить связанные данные - кэш локаций и кэш запоросов и всё, что потребуется впредь
308
      static::cache_clear($cache_id, false);
309
    }
310
  }
311
  public static function cache_lock_get($location_type, $record_id) {
312
    return isset(static::$locks[$location_type][$record_id]);
313
  }
314
  public static function cache_lock_set($location_type, $record_id) {
315
    return static::$locks[$location_type][$record_id] = true; // Не всегда - от результата
316
  }
317
  public static function cache_lock_unset($location_type, $record_id) {
318
    if(isset(static::$locks[$location_type][$record_id]))
319
      unset(static::$locks[$location_type][$record_id]);
320
    return true; // Не всегда - от результата
321
  }
322
  public static function cache_lock_unset_all() {
323
    // Когда будем работать с xcache - это понадобиться, что бы снимать в xcache блокировки с записей
324
    // Пройти по массиву - снять блокировки для кэшера в памяти
325
    static::$locks = array();
326
327
    return true; // Не всегда - от результата
328
  }
329
330
331
332
333
334
  // TODO Вынести в отдельный объект
335
  /**
336
   * Эта функция проверяет статус транзакции
337
   *
338
   * Это - низкоуровневая функция. В нормальном состоянии движка её сообщения никогда не будут видны
339
   *
340
   * @param null|true|false $status Должна ли быть запущена транзакция в момент проверки
341
   *   <p>null - транзакция НЕ должна быть запущена</p>
342
   *   <p>true - транзакция должна быть запущена - для совместимости с $for_update</p>
343
   *   <p>false - всё равно - для совместимости с $for_update</p>
344
   * @return bool Текущий статус транзакции
345
   */
346
  public static function db_transaction_check($status = null) {
347
    $error_msg = false;
348
    if($status && !static::$db_in_transaction) {
349
      $error_msg = 'No transaction started for current operation';
350
    } elseif($status === null && static::$db_in_transaction) {
351
      $error_msg = 'Transaction is already started';
352
    }
353
354
    if($error_msg) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $error_msg of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
355
      // TODO - Убрать позже
356
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_transaction_check() - ' . $error_msg . '</h1>');
357
      $backtrace = debug_backtrace();
358
      array_shift($backtrace);
359
      pdump($backtrace);
360
      die($error_msg);
361
    }
362
363
    return static::$db_in_transaction;
364
  }
365
  public static function db_transaction_start($level = '') {
366
    global $config;
367
368
    static::db_transaction_check(null);
369
370
    $level ? doquery('SET TRANSACTION ISOLATION LEVEL ' . $level) : false;
371
372
    static::$transaction_id++;
373
    doquery('START TRANSACTION');
374
375
    if($config->db_manual_lock_enabled) {
376
      $config->db_loadItem('var_db_manually_locked');
377
      $config->db_saveItem('var_db_manually_locked', SN_TIME_SQL);
378
    }
379
380
    static::$db_in_transaction = true;
381
    static::$locator = array();
382
    static::$queries = array();
383
    //print('<hr/>TRANSACTION START id' . static::$transaction_id . '<br />');
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
384
385
    return static::$transaction_id;
386
  }
387 View Code Duplication
  public static function db_transaction_commit() {
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...
388
    static::db_transaction_check(true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a null|object<true>|false.

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...
389
390
    static::cache_lock_unset_all();
391
    doquery('COMMIT');
392
393
    //print('<br/>TRANSACTION COMMIT id' . static::$transaction_id . '<hr />');
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
394
    static::$db_in_transaction = false;
395
396
    return static::$transaction_id++;
397
  }
398 View Code Duplication
  public static function db_transaction_rollback() {
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...
399
    // static::db_transaction_check(true); // TODO - вообще-то тут тоже надо проверять есть ли транзакция
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
400
    static::cache_lock_unset_all();
401
    doquery('ROLLBACK');
402
403
    //print('<br/>TRANSACTION ROLLBACK id' . static::$transaction_id . '<hr />');
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
404
    static::$db_in_transaction = false;
405
    static::$transaction_id++;
406
    return static::$transaction_id;
407
  }
408
  /**
409
   * Блокирует указанные таблицу/список таблиц
410
   *
411
   * @param string|array $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов
412
   * <p>string - название таблицы для блокировки</p>
413
   * <p>array - массив, где ключ - имя таблицы, а значение - условия блокировки элементов</p>
414
   */
415
  public static function db_lock_tables($tables) {
416
    $tables = is_array($tables) ? $tables : array($tables => '');
417
    foreach($tables as $table_name => $condition) {
418
      self::$db->doquery("SELECT 1 FROM {{{$table_name}}}" . ($condition ? ' WHERE ' . $condition : ''));
419
    }
420
  }
421
  public static function db_query_select($query, $fetch = false, $skip_lock = false) {
422
    $select = strpos(strtoupper($query), 'SELECT') !== false;
423
424
    $query .= $select && $fetch ? ' LIMIT 1' : '';
425
    $query .= $select && !$skip_lock && static::db_transaction_check(false) ? ' FOR UPDATE' : '';
426
427
    $result = self::$db->doquery($query, $fetch);
0 ignored issues
show
Documentation introduced by
$fetch is of type boolean, but the function expects a string.

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...
428
429
    return $result;
430
  }
431
  public static function db_query_update($query) {
432
    return self::$db->doquery($query, false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

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...
433
  }
434
  public static function db_query_delete($query) {
435
    return self::$db->doquery($query, false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

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...
436
  }
437
  public static function db_query_insert($query) {
438
    return self::$db->doquery($query, false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

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...
439
  }
440
441
  /**
442
   * Возвращает информацию о записи по её ID
443
   *
444
   * @param int $location_type
445
   * @param int|array $record_id_unsafe
446
   *    <p>int - ID записи</p>
447
   *    <p>array - запись пользователя с установленным полем P_ID</p>
448
   * @param bool $for_update @deprecated
449
   * @param string $fields @deprecated список полей или '*'/'' для всех полей
450
   * @param bool $skip_lock Указывает на то, что не нужно блокировать запись //TODO и не нужно сохранять в кэше
451
   * @return array|false
452
   *    <p>false - Нет записи с указанным ID</p>
453
   *    <p>array - запись</p>
454
   */
455
  public static function db_get_record_by_id($location_type, $record_id_unsafe, $for_update = false, $fields = '*', $skip_lock = 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...
Unused Code introduced by
The parameter $skip_lock 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...
456
    $id_field = static::$location_info[$location_type][P_ID];
457
    // $record_id = intval(is_array($record_id) && isset($record_id[$id_field]) ? $record_id[$id_field] : $record_id);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
458
    $record_id_safe = idval(is_array($record_id_unsafe) && isset($record_id_unsafe[$id_field]) ? $record_id_unsafe[$id_field] : $record_id_unsafe);
459
460
    return static::db_get_record_list($location_type, "`{$id_field}` = {$record_id_safe}", true, false);
461
  }
462
463
  public static function db_get_record_list($location_type, $filter = '', $fetch = false, $no_return = false) {
464
    $query_cache = &static::$queries[$location_type][$filter];
465
466
    if(!isset($query_cache) || $query_cache === null) {
467
      $location_info = &static::$location_info[$location_type];
468
      $id_field = $location_info[P_ID];
469
      $query_cache = array();
470
471
      if(static::db_transaction_check(false)) {
472
        // Проходим по всем родителям данной записи
473
        foreach($location_info[P_OWNER_INFO] as $owner_data) {
474
          $owner_location_type = $owner_data[P_LOCATION];
475
          $parent_id_list = array();
476
          // Выбираем родителей данного типа и соответствующие ИД текущего типа
477
          $query = static::db_query_select(
478
            "SELECT
479
              distinct({{{$location_info[P_TABLE_NAME]}}}.{$owner_data[P_OWNER_FIELD]}) AS parent_id
480
            FROM {{{$location_info[P_TABLE_NAME]}}}" .
481
            ($filter ? ' WHERE ' . $filter : '') .
482
            ($fetch ? ' LIMIT 1' : ''),
483
            false,
484
            true
485
          );
486
487
          while($row = db_fetch($query)) {
488
            // Исключаем из списка родительских ИД уже заблокированные записи
489
            if(!static::cache_lock_get($owner_location_type, $row['parent_id']))
490
              $parent_id_list[$row['parent_id']] = $row['parent_id'];
491
          }
492
493
          // Если все-таки какие-то записи еще не заблокированы - вынимаем текущие версии из базы
494
          if($indexes_str = implode(',', $parent_id_list)) {
495
            $parent_id_field = static::$location_info[$owner_location_type][P_ID];
496
            static::db_get_record_list($owner_location_type,
497
              $parent_id_field . (count($parent_id_list) > 1 ? " IN ({$indexes_str})" : " = {$indexes_str}"), $fetch, true);
498
          }
499
        }
500
      }
501
502
      $query = static::db_query_select(
503
        "SELECT * FROM {{{$location_info[P_TABLE_NAME]}}}" . (($filter = trim($filter)) ? " WHERE {$filter}" : '')
504
      );
505
      while($row = db_fetch($query)) {
506
        static::cache_set($location_type, $row[$id_field], $row);
507
        $query_cache[$row[$id_field]] = &static::$data[$location_type][$row[$id_field]];
508
      }
509
    }
510
511
    if($no_return) {
512
      return true;
513
    } else {
514
      $result = false;
515
      if(is_array($query_cache)) {
516
        foreach($query_cache as $key => $value) {
517
          $result[$key] = $value;
518
          if($fetch) break;
519
        }
520
      }
521
      return $fetch ? (is_array($result) ? reset($result) : false) : $result;
522
    }
523
  }
524
525
  public static function db_upd_record_by_id($location_type, $record_id, $set) {
526
    if(!($record_id = idval($record_id)) || !($set = trim($set))) return false;
527
528
    $location_info = &static::$location_info[$location_type];
529
    $id_field = $location_info[P_ID];
530
    $table_name = $location_info[P_TABLE_NAME];
531
    if($result = static::db_query_update("UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
532
    {
533
      if(static::$db->db_affected_rows()) {
534
        // Обновляем данные только если ряд был затронут
535
        // TODO - переделать под работу со структурированными $set
536
537
        // Тут именно так, а не cache_unset - что бы в кэшах автоматически обновилась запись. Будет нужно на будущее
538
        static::$data[$location_type][$record_id] = null;
539
        // Вытаскиваем обновленную запись
540
        static::db_get_record_by_id($location_type, $record_id);
541
        static::cache_clear($location_type, false); // Мягкий сброс - только $queries
542
      }
543
    }
544
545
    return $result;
546
  }
547
  public static function db_upd_record_list($location_type, $condition, $set) {
548
    if(!($set = trim($set))) return false;
549
550
    $condition = trim($condition);
551
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
552
553
    if($result = static::db_query_update("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
554
555
      if(static::$db->db_affected_rows()) { // Обновляем данные только если ряд был затронут
556
        // Поскольку нам неизвестно, что и как обновилось - сбрасываем кэш этого типа полностью
557
        // TODO - когда будет структурированный $condition и $set - перепаковывать данные
558
        static::cache_clear($location_type, true);
559
      }
560
    }
561
562
    return $result;
563
  }
564
565
  public static function db_ins_record($location_type, $set) {
566
    $set = trim($set);
567
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
568
    if($result = static::db_query_insert("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
569
      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
570
      {
571
        $record_id = db_insert_id();
572
        // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
573
        $result = static::db_get_record_by_id($location_type, $record_id);
574
        // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
575
        // TODO - когда будет поддержка изменения индексов и локаций - можно будет вызывать её
576
        static::cache_clear($location_type, false); // Мягкий сброс - только $queries
577
      }
578
    }
579
580
    return $result;
581
  }
582
583
  public static function db_del_record_by_id($location_type, $safe_record_id)
584
  {
585
    if(!($safe_record_id = idval($safe_record_id))) return false;
586
587
    $location_info = &static::$location_info[$location_type];
588
    $id_field = $location_info[P_ID];
589
    $table_name = $location_info[P_TABLE_NAME];
590
    if($result = static::db_query_delete("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}"))
591
    {
592
      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
593
      {
594
        static::cache_unset($location_type, $safe_record_id);
595
      }
596
    }
597
598
    return $result;
599
  }
600
  public static function db_del_record_list($location_type, $condition)
601
  {
602
    if(!($condition = trim($condition))) return false;
603
604
    $location_info = &static::$location_info[$location_type];
605
    $table_name = $location_info[P_TABLE_NAME];
606
607
    if($result = static::db_query_delete("DELETE FROM `{{{$table_name}}}` WHERE {$condition}"))
608
    {
609
      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
610
      {
611
        // Обнуление кэша, потому что непонятно, что поменялось
612
        static::cache_clear($location_type);
613
      }
614
    }
615
616
    return $result;
617
  }
618
619
620
621
  // Работа с пользователями
622
  /**
623
   * Возвращает информацию о пользователе по его ID
624
   *
625
   * @param int|array $user_id_unsafe
626
   *    <p>int - ID пользователя</p>
627
   *    <p>array - запись пользователя с установленным полем ['id']</p>
628
   * @param bool $for_update @deprecated
629
   * @param string $fields @deprecated список полей или '*'/'' для всех полей
630
   * @param null $player
631
   * @param bool|null $player Признак выбора записи пользователь типа "игрок"
632
   *    <p>null - Можно выбрать запись любого типа</p>
633
   *    <p>true - Выбирается только запись типа "игрок"</p>
634
   *    <p>false - Выбирается только запись типа "альянс"</p>
635
   * @return array|false
636
   *    <p>false - Нет записи с указанным ID и $player</p>
637
   *    <p>array - запись типа $user</p>
638
   */
639
  public static function db_get_user_by_id($user_id_unsafe, $for_update = false, $fields = '*', $player = null)
640
  {
641
    $user = static::db_get_record_by_id(LOC_USER, $user_id_unsafe, $for_update, $fields);
642
643
    return (is_array($user) &&
644
    (
645
      $player === null
646
      ||
647
      ($player === true && !$user['user_as_ally'])
648
      ||
649
      ($player === false && $user['user_as_ally'])
650
    )) ? $user : false;
651
  }
652
  public static function db_get_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...
653
  {
654
    // TODO Проверить, кстати - а везде ли нужно выбирать юзеров или где-то все-таки ищутся Альянсы ?
655
    if(!($username_unsafe = trim($username_unsafe))) return false;
656
657
    $user = null;
658
    if(is_array(static::$data[LOC_USER]))
659
    foreach(static::$data[LOC_USER] as $user_id => $user_data)
660
    {
661
      if(is_array($user_data) && isset($user_data['username']))
662
      {
663
        // проверяем поле
664
        // TODO Возможно есть смысл всегда искать по strtolower - но может игрок захочет переименоваться с другим регистром? Проверить!
665
        if((!$like && $user_data['username'] == $username_unsafe) || ($like && strtolower($user_data['username']) == strtolower($username_unsafe)))
666
        {
667
          // $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...
668
          $user_as_ally = idval($user_data['user_as_ally']);
669
          if($player === null || ($player === true && !$user_as_ally) || ($player === false && $user_as_ally))
670
          {
671
            $user = $user_data;
672
            break;
673
          }
674
        }
675
      }
676
    }
677
678 View Code Duplication
    if($user === null)
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...
679
    {
680
      // Вытаскиваем запись
681
      $username_safe = db_escape($like ? strtolower($username_unsafe) : $username_unsafe); // тут на самом деле strtolower() лишняя, но пусть будет
682
683
      $user = static::db_query_select(
684
        "SELECT * FROM {{users}} WHERE `username` " . ($like ? 'LIKE' : '='). " '{$username_safe}'",
685
        true
686
      );
687
      static::cache_set(LOC_USER, $user['id'], $user); // В кэш-юзер так же заполнять индексы
688
    }
689
690
    return $user;
691
  }
692
  // UNUSED
693
  public static function db_get_user_by_email($email_unsafe, $use_both = false, $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...
694
    if(!($email_unsafe = strtolower(trim($email_unsafe)))) return false;
695
696
    $user = null;
697
    if(is_array(static::$data[LOC_USER])) {
698
      foreach(static::$data[LOC_USER] as $user_id => $user_data) {
699
        if(is_array($user_data) && isset($user_data['email_2'])) {
700
          // проверяем поле
701
          if(strtolower($user_data['email_2']) == $email_unsafe || ($use_both && strtolower($user_data['email']) == $email_unsafe)) {
702
            $user = $user_data;
703
            break;
704
          }
705
        }
706
      }
707
    }
708
709 View Code Duplication
    if($user === null) {
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...
710
      // Вытаскиваем запись
711
      $email_safe = db_escape($email_unsafe);
712
      $user = static::db_query_select(
713
        "SELECT * FROM {{users}} WHERE LOWER(`email_2`) = '{$email_safe}'" . ($use_both ? " OR LOWER(`email`) = '{$email_safe}'" : ''),
714
        true
715
      );
716
717
      static::cache_set(LOC_USER, $user['id'], $user); // В кэш-юзер так же заполнять индексы
718
    }
719
720
    return $user;
721
  }
722
  public static function db_get_user_by_where($where_safe, $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...
723
    $user = null;
724
    // TODO переделать на индексы
725
726
    if($user === null && !empty($where_safe)) {
727
      // Вытаскиваем запись
728
      $user = static::db_query_select(
729
        "SELECT * FROM {{users}} WHERE {$where_safe}",
730
        true
731
      );
732
733
      static::cache_set(LOC_USER, $user['id'], $user); // В кэш-юзер так же заполнять индексы
734
    }
735
736
    return $user;
737
  }
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753 View Code Duplication
  public static function db_unit_time_restrictions($date = SN_TIME_NOW)
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...
754
  {
755
    $date = is_numeric($date) ? "FROM_UNIXTIME({$date})" : "'{$date}'";
756
    return
757
      "(unit_time_start IS NULL OR unit_time_start <= {$date}) AND
758
    (unit_time_finish IS NULL OR unit_time_finish = '1970-01-01 03:00:00' OR unit_time_finish >= {$date})";
759
  }
760
  public static function db_get_unit_by_id($unit_id, $for_update = false, $fields = '*')
761
  {
762
    // TODO запихивать в $data[LOC_LOCATION][$location_type][$location_id]
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...
763
    $unit = static::db_get_record_by_id(LOC_UNIT, $unit_id, $for_update, $fields);
764
    if(is_array($unit))
765
    {
766
      static::$locator[LOC_UNIT][$unit['unit_location_type']][$unit['unit_location_id']][$unit['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
767
    }
768
769
    return $unit;
770
  }
771
772
  public static function db_get_unit_list_by_location($user_id = 0, $location_type, $location_id)
0 ignored issues
show
Unused Code introduced by
The parameter $user_id 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...
773
  {
774
    if(!($location_type = idval($location_type)) || !($location_id = idval($location_id))) return false;
775
776
    $query_cache = &static::$locator[LOC_UNIT][$location_type][$location_id];
777
    if(!isset($query_cache))
778
    {
779
      $got_data = static::db_get_record_list(LOC_UNIT, "unit_location_type = {$location_type} AND unit_location_id = {$location_id} AND " . static::db_unit_time_restrictions());
780
      if(is_array($got_data))
781
      {
782
        foreach($got_data as $unit_id => $unit_data)
783
        {
784
          // static::$data[LOC_LOCATION][$location_type][$location_id][$unit_data['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% 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...
785
          $query_cache[$unit_data['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
786
        }
787
      }
788
    }
789
790
    $result = false;
791
    if(is_array($query_cache)) {
792
      foreach($query_cache as $key => $value) {
793
        $result[$key] = $value;
794
      }
795
    }
796
797
    return $result;
798
  }
799
  public static function db_get_unit_by_location($user_id = 0, $location_type, $location_id, $unit_snid = 0, $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...
800
  {
801
    static::db_get_unit_list_by_location($user_id, $location_type, $location_id);
802
803
    return $unit_snid ? static::$locator[LOC_UNIT][$location_type][$location_id][$unit_snid] : static::$locator[LOC_UNIT][$location_type][$location_id];
804
  }
805
806
807
808
809
  /*
810
   * С $for_update === true эта функция должна вызываться только из транзакции! Все соответствующие записи в users и planets должны быть уже блокированы!
811
   *
812
   * $que_type
813
   *   !$que_type - все очереди
814
   *   QUE_XXXXXX - конкретная очередь по планете
815
   * $user_id - ID пользователя
816
   * $planet_id
817
   *   $que_type == QUE_RESEARCH - игнорируется
818
   *   null - обработка очередей планет не производится
819
   *   false/0 - обрабатываются очереди всех планет по $user_id
820
   *   (integer) - обрабатываются локальные очереди для планеты. Нужно, например, в обработчике флотов
821
   *   иначе - $que_type для указанной планеты
822
   * $for_update - true == нужно блокировать записи
823
   *
824
   * TODO Работа при !$user_id
825
   * TODO Переформатировать вывод данных, что бы можно было возвращать данные по всем планетам и юзерам в одном запросе: добавить подмассивы 'que', 'planets', 'players'
826
   *
827
   */
828
  public static function db_que_list_by_type_location($user_id, $planet_id = null, $que_type = false, $for_update = 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...
829
  {
830
    if(!$user_id)
831
    {
832
      pdump(debug_backtrace());
833
      die('No user_id for que_get_que()');
834
    }
835
836
    $ques = array();
837
838
    $query = array();
839
840
    if($user_id = idval($user_id))
841
      $query[] = "`que_player_id` = {$user_id}";
842
843
    if($que_type == QUE_RESEARCH || $planet_id === null)
844
      $query[] = "`que_planet_id` IS NULL";
845
    elseif($planet_id)
846
      $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
847
    if($que_type)
848
      $query[] = "`que_type` = {$que_type}";
849
850
    $ques['items'] = static::db_get_record_list(LOC_QUE, implode(' AND ', $query));
851
852
    return que_recalculate($ques);
853
  }
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
  public static function db_changeset_revert()
897
  {
898
    // TODO Для этапа 1 - достаточно чистить только те таблицы, что были затронуты
899
    // Для этапа 2 - чистить только записи
900
    // Для этапа 3 - возвращать всё
901
    static::cache_clear_all(true);
902
  }
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
  // que_process не всегда должна работать в режиме прямой работы с БД !! Она может работать и в режиме эмуляции
939
  // !!!!!!!! После que_get брать не [0] элемент, а first() - тогда можно в индекс элемента засовывать que_id из таблицы
940
941
942
943
944
945
946
947
948
949
950
951
  // TODO - это вообще-то надо хранить в конфигурации
952
  public static function db_get_user_player_username_last_registered() {
953
    $user = static::db_query_select(
954
      'SELECT * FROM `{{users}}` WHERE `user_as_ally` IS NULL ORDER BY `id` DESC',
955
      true
956
    );
957
    static::cache_set(LOC_USER, $user['id'], $user);
958
    return isset($user['username']) ? $user['username'] : '';
959
  }
960
961
  // Это для поиска по кэшу
962
  protected static function db_get_record_by_field($location_type) {
0 ignored issues
show
Unused Code introduced by
The parameter $location_type 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...
963
  }
964
965
  // Для модулей - регистрация юнитов
966
  public static function unit_register() {
967
968
  }
969
970
971
  public static function loadFileSettings () {
972
    $dbsettings = array();
973
974
    require(SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX);
975
    //self::$db_prefix = $dbsettings['prefix'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
976
    self::$cache_prefix = !empty($dbsettings['cache_prefix']) ? $dbsettings['cache_prefix'] : $dbsettings['prefix'];
977
    self::$db_name = $dbsettings['name'];
978
    self::$sn_secret_word = $dbsettings['secretword'];
979
980
    self::services();
981
982
    unset($dbsettings);
983
  }
984
985
  public static function init_global_objects() {
986
    global $sn_cache, $config, $debug;
987
988
    $debug = self::$debug = self::$gc->debug;
0 ignored issues
show
Documentation introduced by
The property debug does not exist on object<Common\GlobalContainer>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
989
    self::$db = self::$gc->db;
0 ignored issues
show
Documentation introduced by
The property db does not exist on object<Common\GlobalContainer>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
990
    self::$db->sn_db_connect();
991
992
    self::$user_options = new userOptions(0);
993
994
    // Initializing global 'cache' object
995
    $sn_cache = static::$cache = self::$gc->cache;
0 ignored issues
show
Documentation introduced by
The property cache does not exist on object<Common\GlobalContainer>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
996
    $tables = classSupernova::$db->schema()->getSnTables();
997
    empty($tables) && die('DB error - cannot find any table. Halting...');
998
999
    // Initializing global "config" object
1000
    $config = static::$config = self::$gc->config;
0 ignored issues
show
Documentation introduced by
The property config does not exist on object<Common\GlobalContainer>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
1001
1002
    // Initializing statics
1003
    Vector::_staticInit(static::$config);
1004
  }
1005
1006
  /**
1007
   * @param int    $newStatus
1008
   * @param string $newMessage
1009
   *
1010
   * @return int
1011
   */
1012
  public static function gameDisable($newStatus = GAME_DISABLE_REASON, $newMessage = '') {
0 ignored issues
show
Unused Code introduced by
The parameter $newMessage 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...
1013
    $old_server_status = intval(self::$config->db_loadItem('game_disable'));
1014
    self::$config->db_saveItem('game_disable', $newStatus);
1015
1016
    return $old_server_status;
1017
  }
1018
1019
  public static function gameEnable() {
1020
    self::$config->db_saveItem('game_disable', GAME_DISABLE_NONE);
1021
  }
1022
1023
  /**
1024
   * Is game disabled?
1025
   *
1026
   * @return bool
1027
   */
1028
  public static function gameIsDisabled() {
1029
    return self::$config->game_disable != GAME_DISABLE_NONE;
0 ignored issues
show
Documentation introduced by
The property game_disable 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...
1030
  }
1031
1032
1033
  public static function services() {
1034
    if(empty(self::$gc)) {
1035
      self::$gc = new GlobalContainer(array(
1036
        'cachePrefix' => self::$cache_prefix,
1037
      ));
1038
    }
1039
1040
    return self::$gc;
1041
  }
1042
1043
}
1044