Completed
Push — work-fleets ( 489db6...8474eb )
by SuperNova.WS
08:27
created

classSupernova   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 314
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 0%

Importance

Changes 43
Bugs 1 Features 1
Metric Value
dl 0
loc 314
rs 10
c 43
b 1
f 1
ccs 0
cts 70
cp 0
wmc 23
lcom 1
cbo 11

6 Methods

Rating   Name   Duplication   Size   Complexity  
A log_file() 0 5 2
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
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
  // que_process не всегда должна работать в режиме прямой работы с БД !! Она может работать и в режиме эмуляции
198
  // !!!!!!!! После que_get брать не [0] элемент, а first() - тогда можно в индекс элемента засовывать que_id из таблицы
199
200
201
  public static function init_0_prepare() {
202
    // Отключаем magic_quotes
203
    ini_get('magic_quotes_sybase') ? die('SN is incompatible with \'magic_quotes_sybase\' turned on. Disable it in php.ini or .htaccess...') : false;
204
    if (@get_magic_quotes_gpc()) {
205
      $gpcr = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
206
      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...
207
        $value = stripslashes($value);
208
      });
209
    }
210
    if (function_exists('set_magic_quotes_runtime')) {
211
      @set_magic_quotes_runtime(0);
212
      @ini_set('magic_quotes_runtime', 0);
213
      @ini_set('magic_quotes_sybase', 0);
214
    }
215
  }
216
217
  public static function init_1_globalContainer() {
218
    static::$gc = new GlobalContainer();
219
    $gc = static::$gc;
220
221
    // Default db
222
    $gc->db = function ($c) {
223
      $db = new db_mysql($c);
224
      $db->sn_db_connect();
225
226
      return $db;
227
    };
228
229
    $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...
230
      return new debug();
231
    };
232
233
    $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...
234
      return new classCache(classSupernova::$cache_prefix);
235
    };
236
237
    $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...
238
      return new classConfig(classSupernova::$cache_prefix);
239
    };
240
241
    $gc->localePlayer = function (GlobalContainer $c) {
242
      return new classLocale($c->config->server_locale_log_usage);
243
    };
244
245
    $gc->dbRowOperator = function ($c) {
246
      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...
247
    };
248
249
    $gc->buddyClass = 'Buddy\BuddyModel';
250
    $gc->buddy = $gc->factory(function (GlobalContainer $c) {
251
      return new $c->buddyClass($c);
252
    });
253
254
    $gc->query = $gc->factory(function (GlobalContainer $c) {
255
      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...
256
    });
257
258
    $gc->unit = $gc->factory(function (GlobalContainer $c) {
259
      return new \V2Unit\V2UnitModel($c);
260
    });
261
262
// 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...
263
//    $container->vector = $container->factory(function (GlobalContainer $c) {
264
//      return new Vector($c->db);
265
//    });
266
  }
267
268
  public static function init_3_load_config_file() {
269
    $dbsettings = array();
270
271
    require(SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX);
272
    self::$cache_prefix = !empty($dbsettings['cache_prefix']) ? $dbsettings['cache_prefix'] : $dbsettings['prefix'];
273
    self::$db_name = $dbsettings['name'];
274
    self::$sn_secret_word = $dbsettings['secretword'];
275
    unset($dbsettings);
276
  }
277
278
  public static function init_global_objects() {
279
    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...
280
    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...
281
    self::$user_options = new userOptions(0);
282
283
    // Initializing global 'cacher' object
284
    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...
285
286
    empty(static::$cache->tables) ? sys_refresh_tablelist() : false;
287
    empty(static::$cache->tables) ? die('DB error - cannot find any table. Halting...') : false;
288
289
    // Initializing global "config" object
290
    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...
291
292
    // Initializing statics
293
    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...
294
  }
295
296
  public static function init_debug_state() {
297
    if ($_SERVER['SERVER_NAME'] == 'localhost' && !defined('BE_DEBUG')) {
298
      define('BE_DEBUG', true);
299
    }
300
    // 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...
301
    define('DEBUG_SQL_ERROR', true); // Выводить в сообщении об ошибке так же полный дамп запросов за сессию. Подойдет любое значение
302
    define('DEBUG_SQL_COMMENT_LONG', true); // Добавлять SQL запрос длинные комментарии. Не зависим от всех остальных параметров. Подойдет любое значение
303
    define('DEBUG_SQL_COMMENT', true); // Добавлять комментарии прямо в SQL запрос. Подойдет любое значение
304
    // Включаем нужные настройки
305
    defined('DEBUG_SQL_ONLINE') && !defined('DEBUG_SQL_ERROR') ? define('DEBUG_SQL_ERROR', true) : false;
306
    defined('DEBUG_SQL_ERROR') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
307
    defined('DEBUG_SQL_COMMENT_LONG') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
308
309
    if (defined('BE_DEBUG') || static::$config->debug) {
310
      @define('BE_DEBUG', true);
311
      @ini_set('display_errors', 1);
312
      @error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
313
    } else {
314
      @define('BE_DEBUG', false);
315
      @ini_set('display_errors', 0);
316
    }
317
318
  }
319
320
}
321