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

classSupernova   D

Complexity

Total Complexity 72

Size/Duplication

Total Lines 602
Duplicated Lines 5.98 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 0%

Importance

Changes 43
Bugs 1 Features 1
Metric Value
c 43
b 1
f 1
dl 36
loc 602
rs 4.7314
ccs 0
cts 218
cp 0
wmc 72
lcom 1
cbo 13

15 Methods

Rating   Name   Duplication   Size   Complexity  
A db_ins_record() 11 17 3
B db_upd_record_list() 0 19 5
B db_ins_field_set() 11 22 4
A db_del_record_by_id() 6 16 4
A db_del_record_list() 8 18 4
A log_file() 0 5 2
A db_lock_tables() 0 6 4
A db_get_record_by_id() 0 6 3
C db_get_record_list() 0 62 17
B db_upd_record_by_id() 0 24 5
A init_0_prepare() 0 15 4
A init_1_globalContainer() 0 50 1
A init_3_load_config_file() 0 9 2
A init_global_objects() 0 17 3
D init_debug_state() 0 23 11

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like classSupernova often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use classSupernova, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
use Vector\Vector;
4
5
use Common\GlobalContainer;
6
7
class classSupernova {
8
  /**
9
   * @var GlobalContainer $gc
10
   */
11
  public static $gc;
12
13
  /**
14
   * ex $sn_mvc
15
   *
16
   * @var array
17
   */
18
  public static $sn_mvc = array();
19
20
  /**
21
   * ex $functions
22
   *
23
   * @var array
24
   */
25
  public static $functions = array();
26
27
  /**
28
   * @var array[] $design
29
   */
30
  public static $design = array(
31
    'bbcodes' => array(),
32
    'smiles'  => array(),
33
  );
34
35
  /**
36
   * Основная БД для доступа к данным
37
   *
38
   * @var db_mysql $db
39
   */
40
  public static $db;
41
  public static $db_name = '';
42
43
  /**
44
   * @var \DBAL\DbTransaction
45
   */
46
  public static $transaction;
47
48
  /**
49
   * @var SnCache $dbCache
50
   */
51
  public static $dbCache;
52
53
  /**
54
   * Настройки из файла конфигурации
55
   *
56
   * @var string
57
   */
58
  public static $cache_prefix = '';
59
60
  public static $sn_secret_word = '';
61
62
  /**
63
   * Конфигурация игры
64
   *
65
   * @var classConfig $config
66
   */
67
  public static $config;
68
69
70
  /**
71
   * Кэш игры
72
   *
73
   * @var classCache $cache
74
   */
75
  public static $cache;
76
77
78
  /**
79
   * @var core_auth $auth
80
   */
81
  public static $auth = null;
82
83
84
  public static $user = array();
85
  /**
86
   * @var userOptions
87
   */
88
  public static $user_options;
89
90
  /**
91
   * @var debug $debug
92
   */
93
  public static $debug = null;
94
95
  public static $options = array();
96
97
  // Кэш индексов - ключ MD5-строка от суммы ключевых строк через | - менять | на что-то другое перед поиском и назад - после поиска
98
  // Так же в индексах могут быть двойные вхождения - например, названия планет да и вообще
99
  // Придумать спецсимвол для NULL
100
101
  /*
102
  TODO Кэш:
103
  1. Всегда дешевле использовать процессор, чем локальную память
104
  2. Всегда дешевле использовать локальную память, чем общую память всех процессов
105
  3. Всегда дешевле использовать общую память всех процессов, чем обращаться к БД
106
107
  Кэш - многоуровневый: локальная память-общая память-БД
108
  БД может быть сверхкэширующей - см. HyperNova. Это реализуется на уровне СН-драйвера БД
109
  Предусмотреть вариант, когда уровни кэширования совпадают, например когда нет xcache и используется общая память
110
  */
111
112
  // TODO Автоматически заполнять эту таблицу. В случае кэша в памяти - делать show table при обращении к таблице
113
  public static $location_info = array(
114
    LOC_USER => array(
115
      P_TABLE_NAME => 'users',
116
      P_ID         => 'id',
117
      P_OWNER_INFO => array(),
118
    ),
119
120
    LOC_PLANET => array(
121
      P_TABLE_NAME => 'planets',
122
      P_ID         => 'id',
123
      P_OWNER_INFO => array(
124
        LOC_USER => array(
125
          P_LOCATION    => LOC_USER,
126
          P_OWNER_FIELD => 'id_owner',
127
        ),
128
      ),
129
    ),
130
131
    LOC_UNIT => array(
132
      P_TABLE_NAME => 'unit',
133
      P_ID         => 'unit_id',
134
      P_OWNER_INFO => array(
135
        LOC_USER => array(
136
          P_LOCATION    => LOC_USER,
137
          P_OWNER_FIELD => 'unit_player_id',
138
        ),
139
      ),
140
    ),
141
142
    LOC_QUE => array(
143
      P_TABLE_NAME => 'que',
144
      P_ID         => 'que_id',
145
      P_OWNER_INFO => array(
146
        array(
147
          P_LOCATION    => LOC_USER,
148
          P_OWNER_FIELD => 'que_player_id',
149
        ),
150
151
        array(
152
          P_LOCATION    => LOC_PLANET,
153
          P_OWNER_FIELD => 'que_planet_id_origin',
154
        ),
155
156
        array(
157
          P_LOCATION    => LOC_PLANET,
158
          P_OWNER_FIELD => 'que_planet_id',
159
        ),
160
      ),
161
    ),
162
163
    LOC_FLEET => array(
164
      P_TABLE_NAME => 'fleets',
165
      P_ID         => 'fleet_id',
166
      P_OWNER_INFO => array(
167
        array(
168
          P_LOCATION    => LOC_USER,
169
          P_OWNER_FIELD => 'fleet_owner',
170
        ),
171
172
        array(
173
          P_LOCATION    => LOC_USER,
174
          P_OWNER_FIELD => 'fleet_target_owner',
175
        ),
176
177
        array(
178
          P_LOCATION    => LOC_PLANET,
179
          P_OWNER_FIELD => 'fleet_start_planet_id',
180
        ),
181
182
        array(
183
          P_LOCATION    => LOC_PLANET,
184
          P_OWNER_FIELD => 'fleet_end_planet_id',
185
        ),
186
      ),
187
    ),
188
  );
189
190
191
  public static function log_file($message, $spaces = 0) {
192
    if (self::$debug) {
193
      self::$debug->log_file($message, $spaces);
194
    }
195
  }
196
197
198
  /**
199
   * Блокирует указанные таблицу/список таблиц
200
   *
201
   * @param string|array $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов
202
   * <p>string - название таблицы для блокировки</p>
203
   * <p>array - массив, где ключ - имя таблицы, а значение - условия блокировки элементов</p>
204
   */
205
  public static function db_lock_tables($tables) {
206
    $tables = is_array($tables) ? $tables : array($tables => '');
207
    foreach ($tables as $table_name => $condition) {
208
      self::$db->doSelect("SELECT 1 FROM {{{$table_name}}}" . ($condition ? ' WHERE ' . $condition : ''));
209
    }
210
  }
211
212
  /**
213
   * Возвращает информацию о записи по её ID
214
   *
215
   * @param int       $location_type
216
   * @param int|array $record_id_unsafe
217
   *    <p>int - ID записи</p>
218
   *    <p>array - запись пользователя с установленным полем P_ID</p>
219
   * @param bool      $for_update @deprecated
220
   * @param string    $fields @deprecated список полей или '*'/'' для всех полей
221
   * @param bool      $skip_lock Указывает на то, что не нужно блокировать запись //TODO и не нужно сохранять в кэше
222
   *
223
   * @return array|false
224
   *    <p>false - Нет записи с указанным ID</p>
225
   *    <p>array - запись</p>
226
   */
227
  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...
228
    $id_field = static::$location_info[$location_type][P_ID];
229
    $record_id_safe = idval(is_array($record_id_unsafe) && isset($record_id_unsafe[$id_field]) ? $record_id_unsafe[$id_field] : $record_id_unsafe);
230
231
    return static::db_get_record_list($location_type, "`{$id_field}` = {$record_id_safe}", true, false);
232
  }
233
234
  public static function db_get_record_list($location_type, $filter = '', $fetch = false, $no_return = false) {
235
    if (SnCache::isQueryCacheByLocationAndFilterEmpty($location_type, $filter)) {
236
      SnCache::queryCacheResetByLocationAndFilter($location_type, $filter);
237
238
      $location_info = &static::$location_info[$location_type];
239
      $id_field = $location_info[P_ID];
240
241
      if (static::$db->getTransaction()->check(false)) {
242
        // Проходим по всем родителям данной записи
243
        foreach ($location_info[P_OWNER_INFO] as $owner_data) {
244
          $owner_location_type = $owner_data[P_LOCATION];
245
          $parent_id_list = array();
246
          // Выбираем родителей данного типа и соответствующие ИД текущего типа
247
          $query = static::$db->doSelect(
248
            "SELECT
249
              distinct({{{$location_info[P_TABLE_NAME]}}}.{$owner_data[P_OWNER_FIELD]}) AS parent_id
250
            FROM {{{$location_info[P_TABLE_NAME]}}}" .
251
            ($filter ? ' WHERE ' . $filter : '') .
252
            ($fetch ? ' LIMIT 1' : ''));
253
          while ($row = db_fetch($query)) {
254
            // Исключаем из списка родительских ИД уже заблокированные записи
255
            if (!SnCache::cache_lock_get($owner_location_type, $row['parent_id'])) {
256
              $parent_id_list[$row['parent_id']] = $row['parent_id'];
257
            }
258
          }
259
260
          // Если все-таки какие-то записи еще не заблокированы - вынимаем текущие версии из базы
261
          if ($indexes_str = implode(',', $parent_id_list)) {
262
            $parent_id_field = static::$location_info[$owner_location_type][P_ID];
263
            static::db_get_record_list($owner_location_type,
264
              $parent_id_field . (count($parent_id_list) > 1 ? " IN ({$indexes_str})" : " = {$indexes_str}"), $fetch, true);
265
          }
266
        }
267
      }
268
269
      $query = static::$db->doSelect(
270
        "SELECT * FROM {{{$location_info[P_TABLE_NAME]}}}" .
271
        (($filter = trim($filter)) ? " WHERE {$filter}" : '')
272
        . " FOR UPDATE"
273
      );
274
      while ($row = db_fetch($query)) {
275
        // Caching record in row cache
276
        SnCache::cache_set($location_type, $row);
277
        // Making ref to cached record in query cache
278
        SnCache::queryCacheSetByFilter($location_type, $filter, $row[$id_field]);
279
      }
280
    }
281
282
    if ($no_return) {
283
      return true;
284
    } else {
285
      $result = false;
286
      foreach (SnCache::getQueriesByLocationAndFilter($location_type, $filter) as $key => $value) {
287
        $result[$key] = $value;
288
        if ($fetch) {
289
          break;
290
        }
291
      }
292
293
      return $fetch ? (is_array($result) ? reset($result) : false) : $result;
294
    }
295
  }
296
297
  /**
298
   * @param int    $location_type
299
   * @param int    $record_id
300
   * @param string $set - SQL SET structure
301
   *
302
   * @return array|bool|mysqli_result|null
303
   */
304
  public static function db_upd_record_by_id($location_type, $record_id, $set) {
305
    if (!($record_id = idval($record_id)) || !($set = trim($set))) {
306
      return false;
307
    }
308
309
    $id_field = static::$location_info[$location_type][P_ID];
310
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
311
    // TODO Как-то вернуть может быть LIMIT 1 ?
312
    if ($result = static::$db->doUpdate("UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) {
313
      if (static::$db->db_affected_rows()) {
314
        // Обновляем данные только если ряд был затронут
315
        // TODO - переделать под работу со структурированными $set
316
317
        // Тут именно так, а не cache_unset - что бы в кэшах автоматически обновилась запись. Будет нужно на будущее
318
        //static::$data[$location_type][$record_id] = null;
0 ignored issues
show
Unused Code Comprehensibility introduced by
79% 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...
319
        SnCache::cacheUnsetElement($location_type, $record_id);
320
        // Вытаскиваем обновленную запись
321
        static::db_get_record_by_id($location_type, $record_id);
322
        SnCache::cache_clear($location_type, false); // Мягкий сброс - только $queries
323
      }
324
    }
325
326
    return $result;
327
  }
328
329
  /**
330
   * @param int    $location_type
331
   * @param string $set
332
   * @param string $condition
333
   *
334
   * @return array|bool|mysqli_result|null
335
   */
336
  public static function db_upd_record_list($location_type, $set, $condition) {
337
    if (!($set = trim($set))) {
338
      return false;
339
    }
340
341
    $condition = trim($condition);
342
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
343
344
    if ($result = static::$db->doUpdate("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
345
346
      if (static::$db->db_affected_rows()) { // Обновляем данные только если ряд был затронут
347
        // Поскольку нам неизвестно, что и как обновилось - сбрасываем кэш этого типа полностью
348
        // TODO - когда будет структурированный $condition и $set - перепаковывать данные
349
        SnCache::cache_clear($location_type, true);
350
      }
351
    }
352
353
    return $result;
354
  }
355
356
  /**
357
   * @param int    $location_type
358
   * @param string $set
359
   *
360
   * @return array|bool|false|mysqli_result|null
361
   */
362
  public static function db_ins_record($location_type, $set) {
363
    $set = trim($set);
364
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
365 View Code Duplication
    if ($result = static::$db->doInsert("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
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...
366
      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
367
      {
368
        $record_id = classSupernova::$db->db_insert_id();
369
        // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
370
        $result = static::db_get_record_by_id($location_type, $record_id);
371
        // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
372
        // TODO - когда будет поддержка изменения индексов и локаций - можно будет вызывать её
373
        SnCache::cache_clear($location_type, false); // Мягкий сброс - только $queries
374
      }
375
    }
376
377
    return $result;
378
  }
379
380
  public static function db_ins_field_set($location_type, $field_set, $serialize = false) {
381
    // TODO multiinsert
382
    !sn_db_field_set_is_safe($field_set) ? $field_set = sn_db_field_set_make_safe($field_set, $serialize) : false;
383
    sn_db_field_set_safe_flag_clear($field_set);
384
    $values = implode(',', $field_set);
385
    $fields = implode(',', array_keys($field_set));
386
387
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
388 View Code Duplication
    if ($result = static::$db->doInsert("INSERT INTO `{{{$table_name}}}` ({$fields}) VALUES ({$values});")) {
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...
389
      if (static::$db->db_affected_rows()) {
390
        // Обновляем данные только если ряд был затронут
391
        $record_id = classSupernova::$db->db_insert_id();
392
        // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
393
        $result = static::db_get_record_by_id($location_type, $record_id);
394
        // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
395
        // TODO - когда будет поддержка изменения индексов и локаций - можно будет вызывать её
396
        SnCache::cache_clear($location_type, false); // Мягкий сброс - только $queries
397
      }
398
    }
399
400
    return $result;
401
  }
402
403
  public static function db_del_record_by_id($location_type, $safe_record_id) {
404
    if (!($safe_record_id = idval($safe_record_id))) {
405
      return false;
406
    }
407
408
    $id_field = static::$location_info[$location_type][P_ID];
409
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
410 View Code Duplication
    if ($result = static::$db->doDelete("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}")) {
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...
411
      // Обновляем данные только если ряд был затронут
412
      if (static::$db->db_affected_rows()) {
413
        SnCache::cache_unset($location_type, $safe_record_id);
414
      }
415
    }
416
417
    return $result;
418
  }
419
420
  public static function db_del_record_list($location_type, $condition) {
421
    if (!($condition = trim($condition))) {
422
      return false;
423
    }
424
425
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
426
427 View Code Duplication
    if ($result = static::$db->doDelete("DELETE FROM `{{{$table_name}}}` WHERE {$condition}")) {
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...
428
      // Обновляем данные только если ряд был затронут
429
      if (static::$db->db_affected_rows()) {
430
        // Обнуление кэша, потому что непонятно, что поменялось
431
        // TODO - когда будет структурированный $condition можно будет делать только cache_unset по нужным записям
432
        SnCache::cache_clear($location_type);
433
      }
434
    }
435
436
    return $result;
437
  }
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
  // que_process не всегда должна работать в режиме прямой работы с БД !! Она может работать и в режиме эмуляции
486
  // !!!!!!!! После que_get брать не [0] элемент, а first() - тогда можно в индекс элемента засовывать que_id из таблицы
487
488
489
  public static function init_0_prepare() {
490
    // Отключаем magic_quotes
491
    ini_get('magic_quotes_sybase') ? die('SN is incompatible with \'magic_quotes_sybase\' turned on. Disable it in php.ini or .htaccess...') : false;
492
    if (@get_magic_quotes_gpc()) {
493
      $gpcr = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
494
      array_walk_recursive($gpcr, function (&$value, $key) {
0 ignored issues
show
Unused Code introduced by
The parameter $key 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...
495
        $value = stripslashes($value);
496
      });
497
    }
498
    if (function_exists('set_magic_quotes_runtime')) {
499
      @set_magic_quotes_runtime(0);
500
      @ini_set('magic_quotes_runtime', 0);
501
      @ini_set('magic_quotes_sybase', 0);
502
    }
503
  }
504
505
  public static function init_1_globalContainer() {
506
    static::$gc = new GlobalContainer();
507
    $gc = static::$gc;
508
509
    // Default db
510
    $gc->db = function ($c) {
511
      $db = new db_mysql($c);
512
      $db->sn_db_connect();
513
514
      return $db;
515
    };
516
517
    $gc->debug = function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
518
      return new debug();
519
    };
520
521
    $gc->cache = function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
522
      return new classCache(classSupernova::$cache_prefix);
523
    };
524
525
    $gc->config = function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
526
      return new classConfig(classSupernova::$cache_prefix);
527
    };
528
529
    $gc->localePlayer = function (GlobalContainer $c) {
530
      return new classLocale($c->config->server_locale_log_usage);
531
    };
532
533
    $gc->dbRowOperator = function ($c) {
534
      return new DbRowDirectOperator($c);
0 ignored issues
show
Unused Code introduced by
The call to DbRowDirectOperator::__construct() has too many arguments starting with $c.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
535
    };
536
537
    $gc->buddyClass = 'Buddy\BuddyModel';
538
    $gc->buddy = $gc->factory(function (GlobalContainer $c) {
539
      return new $c->buddyClass($c);
540
    });
541
542
    $gc->query = $gc->factory(function (GlobalContainer $c) {
543
      return new DbQueryConstructor($c->db);
0 ignored issues
show
Bug introduced by
It seems like $c->db can also be of type object<Closure>; however, DbSqlAware::__construct() does only seem to accept object<db_mysql>|null, 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...
544
    });
545
546
    $gc->unit = $gc->factory(function (GlobalContainer $c) {
547
      return new \V2Unit\V2UnitModel($c);
548
    });
549
550
// TODO
0 ignored issues
show
Unused Code Comprehensibility introduced by
49% 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...
551
//    $container->vector = $container->factory(function (GlobalContainer $c) {
552
//      return new Vector($c->db);
553
//    });
554
  }
555
556
  public static function init_3_load_config_file() {
557
    $dbsettings = array();
558
559
    require(SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX);
560
    self::$cache_prefix = !empty($dbsettings['cache_prefix']) ? $dbsettings['cache_prefix'] : $dbsettings['prefix'];
561
    self::$db_name = $dbsettings['name'];
562
    self::$sn_secret_word = $dbsettings['secretword'];
563
    unset($dbsettings);
564
  }
565
566
  public static function init_global_objects() {
567
    self::$debug = self::$gc->debug;
0 ignored issues
show
Documentation Bug introduced by
It seems like self::$gc->debug can also be of type object<Closure>. However, the property $debug is declared as type object<debug>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
568
    self::$db = self::$gc->db;
0 ignored issues
show
Documentation Bug introduced by
It seems like self::$gc->db can also be of type object<Closure>. However, the property $db is declared as type object<db_mysql>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
569
    self::$user_options = new userOptions(0);
570
571
    // Initializing global 'cacher' object
572
    self::$cache = self::$gc->cache;
0 ignored issues
show
Documentation Bug introduced by
It seems like self::$gc->cache can also be of type object<Closure>. However, the property $cache is declared as type object<classCache>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
573
574
    empty(static::$cache->tables) ? sys_refresh_tablelist() : false;
575
    empty(static::$cache->tables) ? die('DB error - cannot find any table. Halting...') : false;
576
577
    // Initializing global "config" object
578
    static::$config = self::$gc->config;
0 ignored issues
show
Documentation Bug introduced by
It seems like self::$gc->config can also be of type object<Closure>. However, the property $config is declared as type object<classConfig>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
579
580
    // Initializing statics
581
    Vector::_staticInit(static::$config);
0 ignored issues
show
Bug introduced by
It seems like static::$config can also be of type object<Closure>; however, Vector\Vector::_staticInit() does only seem to accept object<classConfig>, 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...
582
  }
583
584
  public static function init_debug_state() {
585
    if ($_SERVER['SERVER_NAME'] == 'localhost' && !defined('BE_DEBUG')) {
586
      define('BE_DEBUG', true);
587
    }
588
    // define('DEBUG_SQL_ONLINE', true); // Полный дамп запросов в рил-тайме. Подойдет любое значение
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...
589
    define('DEBUG_SQL_ERROR', true); // Выводить в сообщении об ошибке так же полный дамп запросов за сессию. Подойдет любое значение
590
    define('DEBUG_SQL_COMMENT_LONG', true); // Добавлять SQL запрос длинные комментарии. Не зависим от всех остальных параметров. Подойдет любое значение
591
    define('DEBUG_SQL_COMMENT', true); // Добавлять комментарии прямо в SQL запрос. Подойдет любое значение
592
    // Включаем нужные настройки
593
    defined('DEBUG_SQL_ONLINE') && !defined('DEBUG_SQL_ERROR') ? define('DEBUG_SQL_ERROR', true) : false;
594
    defined('DEBUG_SQL_ERROR') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
595
    defined('DEBUG_SQL_COMMENT_LONG') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
596
597
    if (defined('BE_DEBUG') || static::$config->debug) {
598
      @define('BE_DEBUG', true);
599
      @ini_set('display_errors', 1);
600
      @error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
601
    } else {
602
      @define('BE_DEBUG', false);
603
      @ini_set('display_errors', 0);
604
    }
605
606
  }
607
608
}
609