Completed
Push — trunk ( 5a98ee...c2d255 )
by SuperNova.WS
04:09
created

uni_render_planet_full()   C

Complexity

Conditions 10
Paths 257

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 12
nc 257
nop 4
dl 0
loc 18
rs 6
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
function uni_create_planet_get_density($position_data, $user_row, $planet_sectors) {
4
  $density_list = sn_get_groups('planet_density');
5
  $density_min = reset($density_list);
6
  unset($density_list[PLANET_DENSITY_NONE]);
7
8
  $possible_cores = array();
9
  $probability = 0;
10
  foreach ($density_list as $possible_core_id => $core_data) {
11
    if (!$core_data[UNIT_PLANET_DENSITY_RARITY]) {
12
      continue;
13
    }
14
15
    if (
16
      // Core type exists
17
      in_array($possible_core_id, $position_data['core_types'])
18
      // Limit core type with planet sector count
19
      && $planet_sectors < $density_list[$possible_core_id][UNIT_PLANET_DENSITY_MAX_SECTORS]
20
      // Limit core type with player AstroTech level
21
      && (empty($user_row) || mrc_get_level($user_row, null, TECH_ASTROTECH) >= $density_list[$possible_core_id][UNIT_PLANET_DENSITY_MIN_ASTROTECH])
22
    ) {
23
      // Фильтруем типы ядер, которые не подходят по размеру планеты
24
      $probability += $density_list[$possible_core_id][UNIT_PLANET_DENSITY_RARITY];
25
      $possible_cores[$possible_core_id] = array(
26
        UNIT_PLANET_DENSITY_INDEX  => $possible_core_id,
27
        UNIT_PLANET_DENSITY_RARITY => $probability,
28
        UNIT_PLANET_DENSITY        => mt_rand($density_min[UNIT_PLANET_DENSITY], $density_list[$possible_core_id][UNIT_PLANET_DENSITY] - 1),
29
      );
30
    }
31
    $density_min = $density_list[$possible_core_id];
32
  }
33
34
  $random = mt_rand(1, $probability);
35
  $selected_core = null;
36
  foreach ($possible_cores as $core_type => $core_info) {
37
    if ($random <= $core_info[UNIT_PLANET_DENSITY_RARITY]) {
38
      $selected_core = $core_info;
39
      break;
40
    }
41
  }
42
43
  return $selected_core;
44
}
45
46
/**
47
 * @param int        $Galaxy
48
 * @param int        $System
49
 * @param int        $Position
50
 * @param int        $PlanetOwnerID
51
 * @param string     $planet_name_unsafe
52
 * @param bool|false $HomeWorld
53
 * @param array      $options
54
 *
55
 * @return bool
56
 */
57
function uni_create_planet($Galaxy, $System, $Position, $PlanetOwnerID, $planet_name_unsafe = '', $HomeWorld = false, $options = array()) {
58
  global $lang, $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
59
60
  $Position = intval($Position);
61
62
  if (!isset($options['skip_check']) && DBStaticPlanet::db_planet_by_gspt($Galaxy, $System, $Position, PT_PLANET, true, '`id`')) {
63
    return false;
64
  }
65
66
  $user_row = !empty($options['user_row']) && is_array($options['user_row']) ? $options['user_row'] : db_user_by_id($PlanetOwnerID);
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

66
  $user_row = !empty($options['user_row']) && is_array($options['user_row']) ? $options['user_row'] : /** @scrutinizer ignore-deprecated */ db_user_by_id($PlanetOwnerID);
Loading history...
67
68
69
  $planet_generator = sn_get_groups('planet_generator');
70
71
  if ($HomeWorld) {
72
    $position_data = $planet_generator[0];
73
  } else {
74
    $position_data = $planet_generator[$Position >= UNIVERSE_RANDOM_PLANET_START || $Position < 1 ? UNIVERSE_RANDOM_PLANET_START : $Position];
75
    if ($Position >= UNIVERSE_RANDOM_PLANET_START) {
76
      // Корректируем температуру для планеты-странника
77
      $position_data['t_max_max'] -= UNIVERSE_RANDOM_PLANET_TEMPERATURE_DECREASE * ($Position - UNIVERSE_RANDOM_PLANET_START);
78
    }
79
  }
80
81
  $planet_images = sn_get_groups('planet_images');
82
  $planet_image = $position_data['planet_images'][mt_rand(0, count($position_data['planet_images']) - 1)];
83
  $planet_image .= 'planet' . $planet_images[$planet_image][mt_rand(0, count($planet_images[$planet_image]) - 1)];
84
85
  $t_max = sn_rand_gauss_range($position_data['t_max_min'], $position_data['t_max_max'], true, 1.3, true);
0 ignored issues
show
Bug introduced by
1.3 of type double is incompatible with the type integer expected by parameter $strict of sn_rand_gauss_range(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

85
  $t_max = sn_rand_gauss_range($position_data['t_max_min'], $position_data['t_max_max'], true, /** @scrutinizer ignore-type */ 1.3, true);
Loading history...
86
  $t_min = $t_max - sn_rand_gauss_range($position_data['t_delta_min'], $position_data['t_delta_max'], true, 1.3, true);
87
88
  $planet_sectors = sn_rand_gauss_range($position_data['size_min'], $position_data['size_max'], true, 1.7, true);
89
//  $planet_diameter = round(pow($planet_sectors, 2) * 1000);
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...
90
  $planet_diameter = round(sqrt($planet_sectors) * 1000);
91
92
  $core_info = uni_create_planet_get_density($position_data, $user_row, $planet_sectors);
93
94
  $planet_name_unsafe = $user_row['username'] . ' ' . ($planet_name_unsafe ? $planet_name_unsafe : $lang['sys_colo_defaultname']);
95
96
  $planet['name'] = db_escape(strip_tags(trim($planet_name_unsafe)));
0 ignored issues
show
Comprehensibility Best Practice introduced by
$planet was never initialized. Although not strictly required by PHP, it is generally a good practice to add $planet = array(); before regardless.
Loading history...
97
  $planet['id_owner'] = $PlanetOwnerID;
98
  $planet['last_update'] = SN_TIME_NOW;
99
  $planet['image'] = $planet_image;
100
101
  $planet['galaxy'] = $Galaxy;
102
  $planet['system'] = $System;
103
  $planet['planet'] = $planet['position_original'] = $Position;
104
  $planet['planet_type'] = PT_PLANET;
105
106
  $planet['diameter'] = $planet_diameter;
107
  $planet['field_max'] = $planet['field_max_original'] = $planet_sectors;
108
  $planet['density'] = $core_info[UNIT_PLANET_DENSITY];
109
  $planet['density_index'] = $core_info[UNIT_PLANET_DENSITY_INDEX];
110
  $planet['temp_min'] = $planet['temp_min_original'] = $t_min;
111
  $planet['temp_max'] = $planet['temp_max_original'] = $t_max;
112
113
  $planet['metal'] = $config->eco_planet_starting_metal;
114
  $planet['crystal'] = $config->eco_planet_starting_crystal;
115
  $planet['deuterium'] = $config->eco_planet_starting_deuterium;
116
  $planet['metal_max'] = $config->eco_planet_storage_metal;
117
  $planet['crystal_max'] = $config->eco_planet_storage_crystal;
118
  $planet['deuterium_max'] = $config->eco_planet_storage_deuterium;
119
120
  $density_info_resources = &$density_list[$core_info[UNIT_PLANET_DENSITY_INDEX]][UNIT_RESOURCES];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $density_list seems to be never defined.
Loading history...
121
  $planet['metal_perhour'] = $config->metal_basic_income * $density_info_resources[RES_METAL];
122
  $planet['crystal_perhour'] = $config->crystal_basic_income * $density_info_resources[RES_CRYSTAL];
123
  $planet['deuterium_perhour'] = $config->deuterium_basic_income * $density_info_resources[RES_DEUTERIUM];
124
125
  $RetValue = classSupernova::db_ins_record(LOC_PLANET,
126
    "`name` = '{$planet['name']}', `id_owner` = '{$planet['id_owner']}', `last_update` = '{$planet['last_update']}', `image` = '{$planet['image']}',
127
      `galaxy` = '{$planet['galaxy']}', `system` = '{$planet['system']}', `planet` = '{$planet['planet']}', `planet_type` = '{$planet['planet_type']}', `position_original` = '{$planet['position_original']}',
128
      `diameter` = '{$planet['diameter']}', `field_max` = '{$planet['field_max']}', `field_max_original` = '{$planet['field_max_original']}',
129
      `density` = '{$planet['density']}', `density_index` = '{$planet['density_index']}',
130
      `temp_min` = '{$planet['temp_min']}', `temp_max` = '{$planet['temp_max']}', `temp_min_original` = '{$planet['temp_min_original']}', `temp_max_original` = '{$planet['temp_max_original']}',
131
      `metal` = '{$planet['metal']}', `metal_perhour` = '{$planet['metal_perhour']}', `metal_max` = '{$planet['metal_max']}',
132
      `crystal` = '{$planet['crystal']}', `crystal_perhour` = '{$planet['crystal_perhour']}', `crystal_max` = '{$planet['crystal_max']}',
133
      `deuterium` = '{$planet['deuterium']}', `deuterium_perhour` = '{$planet['deuterium_perhour']}', `deuterium_max` = '{$planet['deuterium_max']}'"
134
  );
135
136
  return is_array($RetValue) ? $RetValue['id'] : false; // OK
0 ignored issues
show
introduced by
The condition is_array($RetValue) can never be true.
Loading history...
137
}
138
139
/**
140
 * uni_create_moon.php
141
 *
142
 * UNI: Create moon record
143
 *
144
 * V2.1  - copyright (c) 2010-2011 by Gorlum for http://supernova.ws
145
 *   [~] Renamed CreateOneMoonRecord to uni_create_moon
146
 *   [-] Removed unsed $MoonID parameter from call
147
 *   [~] PCG1 compliant
148
 * V2.0  - copyright (c) 2010 by Gorlum for http://supernova.ws
149
 *   [+] Deep rewrite to rid of using `galaxy` and `lunas` tables greatly reduce numbers of SQL-queries
150
 * @version   1.1
151
 * @copyright 2008
152
 */
153
154
/**
155
 * @param        $pos_galaxy
156
 * @param        $pos_system
157
 * @param        $pos_planet
158
 * @param        $user_id
159
 * @param int    $size <p><b>0</b> - random moon size</p>
160
 * @param bool   $update_debris
161
 * @param array  $options ['name' => (str), 'image' => (str)]
162
 *
163
 * @return array
164
 */
165
function uni_create_moon($pos_galaxy, $pos_system, $pos_planet, $user_id, $size = 0, $update_debris = true, $options = []) {
166
  global $lang;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
167
168
  $moon_row = [];
169
  $moon = DBStaticPlanet::db_planet_by_gspt($pos_galaxy, $pos_system, $pos_planet, PT_MOON, false, 'id');
170
  if (empty($moon['id'])) {
171
    $moon_planet = DBStaticPlanet::db_planet_by_gspt($pos_galaxy, $pos_system, $pos_planet, PT_PLANET, true, '`id`, `temp_min`, `temp_max`, `name`, `debris_metal`, `debris_crystal`');
172
173
    if ($moon_planet['id']) {
174
      $base_storage_size = BASE_STORAGE_SIZE;
175
176
      empty($size) ? $size = \Universe::moonSizeRandom() : false;
177
178
      $temp_min = $moon_planet['temp_min'] - rand(10, 45);
179
      $temp_max = $temp_min + 40;
180
181
      $moon_name = !empty($options['name']) ? $options['name'] : "{$moon_planet['name']} {$lang['sys_moon']}";
182
      $moon_name_safe = db_escape($moon_name);
183
184
      $field_max = ceil($size / 1000);
185
186
      $moon_image = !empty($options['image']) ? $options['image'] : 'mond';
187
188
      $moon_row = classSupernova::db_ins_record(LOC_PLANET,
189
        "`id_owner` = '{$user_id}', `parent_planet` = '{$moon_planet['id']}', `name` = '{$moon_name_safe}', `last_update` = " . SN_TIME_NOW . ", `image` = '{$moon_image}',
190
          `galaxy` = '{$pos_galaxy}', `system` = '{$pos_system}', `planet` = '{$pos_planet}', `planet_type` = " . PT_MOON . ",
191
          `diameter` = '{$size}', `field_max` = '{$field_max}', `density` = 2500, `density_index` = 2, `temp_min` = '{$temp_min}', `temp_max` = '{$temp_max}',
192
          `metal` = '0', `metal_perhour` = '0', `metal_max` = '{$base_storage_size}',
193
          `crystal` = '0', `crystal_perhour` = '0', `crystal_max` = '{$base_storage_size}',
194
          `deuterium` = '0', `deuterium_perhour` = '0', `deuterium_max` = '{$base_storage_size}'"
195
      );
196
197
      if ($update_debris) {
198
        $debris_spent = round($size / 1000 * Universe::moonPercentCostInDebris());
199
        $metal_spent = round(min($moon_planet['debris_metal'], $debris_spent * mt_rand(50 * 1000, 75 * 1000) / (100 * 1000))); // Trick for higher mt_rand resolution
200
        $crystal_spent = min($moon_planet['debris_crystal'], $debris_spent - $metal_spent);
201
        $metal_spent = min($moon_planet['debris_metal'], $debris_spent - $crystal_spent); // Need if crystal less then their part
202
        DBStaticPlanet::db_planet_set_by_id($moon_planet['id'], "`debris_metal` = GREATEST(0, `debris_metal` - {$metal_spent}), `debris_crystal` = GREATEST(0, `debris_crystal` - {$crystal_spent})");
203
      }
204
    }
205
  }
206
207
  return $moon_row;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $moon_row also could return the type boolean|mysqli_result which is incompatible with the documented return type array.
Loading history...
208
}
209
210
/*
211
 *
212
 * @function SetSelectedPlanet
213
 *
214
 * @history
215
 *
216
 * 4 - copyright (c) 2014 by Gorlum for http://supernova.ws
217
 *   [!] Full rewrote from scratch
218
 * 3 - copyright (c) 2009-2011 by Gorlum for http://supernova.ws
219
 *   [+] Added handling case when current_planet does not exists or didn't belong to user
220
 *   [+] Moved from SetSelectedPlanet.php
221
 *   [+] Function now return
222
 *   [~] Complies with PCG1
223
 * 2 - copyright (c) 2009-2011 by Gorlum for http://supernova.ws
224
 *   [~] Security checked for SQL-injection
225
 * 1 - copyright 2008 By Chlorel for XNova
226
 *
227
 */
228
function SetSelectedPlanet(&$user) {
229
  $planet_row['id'] = $user['current_planet'];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$planet_row was never initialized. Although not strictly required by PHP, it is generally a good practice to add $planet_row = array(); before regardless.
Loading history...
230
231
  // Пытаемся переключить на новую планету
232
  if (($selected_planet = sys_get_param_id('cp')) && $selected_planet != $user['current_planet']) {
233
    $planet_row = DBStaticPlanet::db_planet_by_id_and_owner($selected_planet, $user['id'], false, 'id');
234
  } else {
235
    $planet_row = DBStaticPlanet::db_planet_by_id($planet_row['id']);
236
  }
237
238
  // Если новая планета не найдена или было переключения - проверяем текущую выбранную планету
239
  if (!isset($planet_row['id'])) // || $planet_row['id'] != $user['current_planet']
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...
240
  {
241
    $planet_row = DBStaticPlanet::db_planet_by_id_and_owner($user['current_planet'], $user['id'], false, 'id');
242
    // Если текущей планеты не существует - выставляем Столицу
243
    if (!isset($planet_row['id'])) {
244
      $planet_row = DBStaticPlanet::db_planet_by_id_and_owner($user['id_planet'], $user['id'], false, 'id');
245
      // Если и столицы не существует - значит что-то очень не так с записью пользователя
246
      if (!isset($planet_row['id'])) {
247
        global $debug;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
248
        $debug->error("User ID {$user['id']} has Capital planet {$user['id_planet']} but this planet does not exists", 'User record error', 502);
249
      }
250
    }
251
  }
252
253
  // Если производилось переключение планеты - делаем запись в юзере
254
  if ($user['current_planet'] != $planet_row['id']) {
255
    db_user_set_by_id($user['id'], "`current_planet` = '{$planet_row['id']}'");
0 ignored issues
show
Deprecated Code introduced by
The function db_user_set_by_id() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

255
    /** @scrutinizer ignore-deprecated */ db_user_set_by_id($user['id'], "`current_planet` = '{$planet_row['id']}'");
Loading history...
256
    $user['current_planet'] = $planet_row['id'];
257
  }
258
259
  return $user['current_planet'];
260
}
261
262
// ----------------------------------------------------------------------------------------------------------------
263
function uni_render_coordinates($from, $prefix = '') {
264
  return "[{$from[$prefix . 'galaxy']}:{$from[$prefix . 'system']}:{$from[$prefix . 'planet']}]";
265
}
266
267
function uni_render_planet($from) {
268
  return "{$from['name']} [{$from['galaxy']}:{$from['system']}:{$from['planet']}]";
269
}
270
271
function uni_render_planet_full($from, $prefix = '', $html_safe = true, $include_id = false) {
272
  global $lang;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
273
274
  if (!$from['id']) {
275
    $result = $lang['sys_planet_expedition'];
276
  } else {
277
    $from_planet_id = $include_id ? (
278
      'ID {' . ($from['id'] ? $from['id'] : ($from[$prefix . 'planet_id'] ? $from[$prefix . 'planet_id'] : 0)) . '} '
279
    ) : '';
280
281
    $from_planet_type = $from['planet_type'] ? $from['planet_type'] : ($from[$prefix . 'type'] ? $from[$prefix . 'type'] : 0);
282
    $from_planet_type = ($from_planet_type ? ' ' . $lang['sys_planet_type_sh'][$from_planet_type] : '');
283
284
    $result = $from_planet_id . uni_render_coordinates($from, $prefix) . $from_planet_type . ($from['name'] ? ' ' . $from['name'] : '');
285
    $result = $html_safe ? HelperString::htmlEncode($result, HTML_ENCODE_PREFORM | HTML_ENCODE_SPACE) : $result;
286
  }
287
288
  return $result;
289
}
290
291
/**
292
 * @param \Planet\Planet $from
293
 *
294
 * @return string
295
 */
296
function uni_render_coordinates_planet_object($from) {
297
  return is_object($from) ? "[{$from->galaxy}:{$from->system}:{$from->planet}]" : '[-:-:-]';
298
}
299
300
301
/**
302
 * @param \Planet\Planet $from
303
 * @param bool           $html_safe
304
 * @param bool           $include_id
305
 *
306
 * @return mixed|null|string
307
 */
308
function uni_render_planet_object_full($from, $html_safe = true, $include_id = false) {
309
  if (empty($from->id)) {
310
    $result = classSupernova::$lang['sys_planet_expedition'];
311
  } else {
312
    $from_planet_id = $include_id ? (
313
      'ID {' . ($from->id ? $from->id : 0) . '} '
314
    ) : '';
315
316
    $from_planet_type = isset($from->planet_type) ? $from->planet_type : 0;
317
    $from_planet_type = ($from_planet_type ? ' ' . classSupernova::$lang['sys_planet_type_sh'][$from_planet_type] : '');
318
319
    $result = $from_planet_id . uni_render_coordinates_planet_object($from) . $from_planet_type . (isset($from->name) ? ' ' . $from->name : '');
320
    $result = $html_safe ? HelperString::htmlEncode($result, HTML_ENCODE_PREFORM | HTML_ENCODE_SPACE) : $result;
321
  }
322
323
  return $result;
324
}
325
326
function uni_render_coordinates_url($from, $prefix = '', $page = 'galaxy.php') {
327
  return $page . (strpos($page, '?') === false ? '?' : '&') . "galaxy={$from[$prefix . 'galaxy']}&system={$from[$prefix . 'system']}&planet={$from[$prefix . 'planet']}";
328
}
329
330
function uni_render_coordinates_href($from, $prefix = '', $mode = 0, $fleet_type = '') {
331
  return '<a href="' . uni_render_coordinates_url($from, $prefix, "galaxy.php?mode={$mode}") . '"' . ($fleet_type ? " {$fleet_type}" : '') . '>' . uni_render_coordinates($from, $prefix) . '</a>';
332
}
333
334
function uni_get_time_to_jump($moon_row) {
335
  $jump_gate_level = mrc_get_level($user, $moon_row, STRUC_MOON_GATE);
336
337
  return $jump_gate_level ? max(0, $moon_row['last_jump_time'] + abs(60 * 60 / $jump_gate_level) - SN_TIME_NOW) : 0;
338
}
339
340
function uni_coordinates_valid($coordinates, $prefix = '') {
341
  global $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
342
343
  // array_walk($coordinates, 'intval');
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...
344
  $coordinates["{$prefix}galaxy"] = intval($coordinates["{$prefix}galaxy"]);
345
  $coordinates["{$prefix}system"] = intval($coordinates["{$prefix}system"]);
346
  $coordinates["{$prefix}planet"] = intval($coordinates["{$prefix}planet"]);
347
348
  return
349
    isset($coordinates["{$prefix}galaxy"]) && $coordinates["{$prefix}galaxy"] > 0 && $coordinates["{$prefix}galaxy"] <= $config->game_maxGalaxy &&
350
    isset($coordinates["{$prefix}system"]) && $coordinates["{$prefix}system"] > 0 && $coordinates["{$prefix}system"] <= $config->game_maxSystem &&
351
    isset($coordinates["{$prefix}planet"]) && $coordinates["{$prefix}planet"] > 0 && $coordinates["{$prefix}planet"] <= $config->game_maxPlanet;
352
}
353
354
function uni_planet_teleport_check($user, $planetrow, $new_coordinates = null) {
355
  global $lang, $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
356
357
  try {
358
    if ($planetrow['planet_teleport_next'] && $planetrow['planet_teleport_next'] > SN_TIME_NOW) {
359
      throw new exception($lang['ov_teleport_err_cooldown'], ERR_ERROR);
360
    }
361
362
    if (mrc_get_level($user, false, RES_DARK_MATTER) < $config->planet_teleport_cost) {
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array expected by parameter $planet of mrc_get_level(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

362
    if (mrc_get_level($user, /** @scrutinizer ignore-type */ false, RES_DARK_MATTER) < $config->planet_teleport_cost) {
Loading history...
363
      throw new exception($lang['ov_teleport_err_no_dark_matter'], ERR_ERROR);
364
    }
365
366
    // TODO: Replace quick-check with using gathered flying fleet data
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...
367
//    $incoming = doquery("SELECT COUNT(*) AS incoming FROM {{fleets}} WHERE
368
//      (fleet_start_galaxy = {$planetrow['galaxy']} and fleet_start_system = {$planetrow['system']} and fleet_start_planet = {$planetrow['planet']})
369
//      or
370
//      (fleet_end_galaxy = {$planetrow['galaxy']} and fleet_end_system = {$planetrow['system']} and fleet_end_planet = {$planetrow['planet']})", true);
371
//    if(!empty($incoming['incoming'])) {
372
//      throw new exception($lang['ov_teleport_err_fleet'], ERR_ERROR);
373
//    }
374
    if (fleet_count_incoming($planetrow['galaxy'], $planetrow['system'], $planetrow['planet'])) {
375
      throw new exception($lang['ov_teleport_err_fleet'], ERR_ERROR);
376
    }
377
378
    //$incoming = doquery("SELECT COUNT(*) AS incoming FROM {{iraks}} WHERE fleet_end_galaxy = {$planetrow['galaxy']} and fleet_end_system = {$planetrow['system']} and fleet_end_planet = {$planetrow['planet']}", true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
379
    //if($incoming['incoming']) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
89% 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...
380
    //  throw new exception($lang['ov_teleport_err_fleet'], ERR_ERROR);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
381
    //}
382
383
    if (is_array($new_coordinates)) {
384
      $new_coordinates['planet_type'] = PT_PLANET;
385
      $incoming = DBStaticPlanet::db_planet_by_vector($new_coordinates, '', true, 'id');
386
      if ($incoming['id']) {
387
        throw new exception($lang['ov_teleport_err_destination_busy'], ERR_ERROR);
388
      }
389
    }
390
391
    $response = array(
392
      'result'  => ERR_NONE,
393
      'message' => '',
394
    );
395
  } catch (exception $e) {
396
    $response = array(
397
      'result'  => $e->getCode(),
398
      'message' => $e->getMessage(),
399
    );
400
  }
401
402
  return $response;
403
}
404