Completed
Push — work-fleets ( 04acf9...8f8df9 )
by SuperNova.WS
07:02
created

uni_functions.php ➔ uni_create_planet()   C

Complexity

Conditions 11
Paths 145

Size

Total Lines 70
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 47
c 1
b 0
f 0
nc 145
nop 7
dl 0
loc 70
rs 5.3599

How to fix   Long Method    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
use Vector\Vector;
4
5
function uni_create_planet_get_density($position_data, $user_row, $planet_sectors) {
6
  $density_list = sn_get_groups('planet_density');
7
  $density_min = reset($density_list);
8
  unset($density_list[PLANET_DENSITY_NONE]);
9
10
  $possible_cores = array();
11
  $probability = 0;
12
  foreach($density_list as $possible_core_id => $core_data) {
13
    if(!$core_data[UNIT_PLANET_DENSITY_RARITY]) {
14
      continue;
15
    }
16
17
    if(
18
      // Core type exists
19
      in_array($possible_core_id, $position_data['core_types'])
20
      // Limit core type with planet sector count
21
      && $planet_sectors < $density_list[$possible_core_id][UNIT_PLANET_DENSITY_MAX_SECTORS]
22
      // Limit core type with player AstroTech level
23
      && (empty($user_row) || mrc_get_level($user_row, null, TECH_ASTROTECH) >= $density_list[$possible_core_id][UNIT_PLANET_DENSITY_MIN_ASTROTECH])
24
    ) {
25
      // Фильтруем типы ядер, которые не подходят по размеру планеты
26
      $probability += $density_list[$possible_core_id][UNIT_PLANET_DENSITY_RARITY];
27
      $possible_cores[$possible_core_id] = array(
28
        UNIT_PLANET_DENSITY_INDEX  => $possible_core_id,
29
        UNIT_PLANET_DENSITY_RARITY => $probability,
30
        UNIT_PLANET_DENSITY        => mt_rand($density_min[UNIT_PLANET_DENSITY], $density_list[$possible_core_id][UNIT_PLANET_DENSITY] - 1),
31
      );
32
    }
33
    $density_min = $density_list[$possible_core_id];
34
  }
35
36
  $random = mt_rand(1, $probability);
37
  $selected_core = null;
38
  foreach($possible_cores as $core_type => $core_info) {
39
    if($random <= $core_info[UNIT_PLANET_DENSITY_RARITY]) {
40
      $selected_core = $core_info;
41
      break;
42
    }
43
  }
44
45
  return $selected_core;
46
}
47
48
/**
49
 * @param int        $Galaxy
50
 * @param int        $System
51
 * @param int        $Position
52
 * @param int        $PlanetOwnerID
53
 * @param string     $planet_name_unsafe
54
 * @param bool|false $HomeWorld
55
 * @param array      $options
56
 *
57
 * @return bool
58
 */
59
function uni_create_planet($Galaxy, $System, $Position, $PlanetOwnerID, $planet_name_unsafe = '', $HomeWorld = false, $options = array()) {
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'] : DBStaticUser::db_user_by_id($PlanetOwnerID);
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);
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 : classLocale::$lang['sys_colo_defaultname']);
95
96
  $planet['name'] = trim(strip_tags($planet_name_unsafe));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$planet was never initialized. Although not strictly required by PHP, it is generally a good practice to add $planet = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

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'] = classSupernova::$config->eco_planet_starting_metal;
0 ignored issues
show
Documentation introduced by
The property eco_planet_starting_metal does not exist on object<classConfig>. 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...
114
  $planet['crystal'] = classSupernova::$config->eco_planet_starting_crystal;
0 ignored issues
show
Documentation introduced by
The property eco_planet_starting_crystal does not exist on object<classConfig>. 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...
115
  $planet['deuterium'] = classSupernova::$config->eco_planet_starting_deuterium;
0 ignored issues
show
Documentation introduced by
The property eco_planet_starting_deuterium does not exist on object<classConfig>. 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...
116
  $planet['metal_max'] = classSupernova::$config->eco_planet_storage_metal;
0 ignored issues
show
Documentation introduced by
The property eco_planet_storage_metal does not exist on object<classConfig>. 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...
117
  $planet['crystal_max'] = classSupernova::$config->eco_planet_storage_crystal;
0 ignored issues
show
Documentation introduced by
The property eco_planet_storage_crystal does not exist on object<classConfig>. 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...
118
  $planet['deuterium_max'] = classSupernova::$config->eco_planet_storage_deuterium;
0 ignored issues
show
Documentation introduced by
The property eco_planet_storage_deuterium does not exist on object<classConfig>. 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...
119
120
  $density_info_resources = &$density_list[$core_info[UNIT_PLANET_DENSITY_INDEX]][UNIT_RESOURCES];
0 ignored issues
show
Bug introduced by
The variable $density_list does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
121
  $planet['metal_perhour'] = classSupernova::$config->metal_basic_income * $density_info_resources[RES_METAL];
122
  $planet['crystal_perhour'] = classSupernova::$config->crystal_basic_income * $density_info_resources[RES_CRYSTAL];
123
  $planet['deuterium_perhour'] = classSupernova::$config->deuterium_basic_income * $density_info_resources[RES_DEUTERIUM];
124
125
  $RetValue = classSupernova::$gc->cacheOperator->db_ins_record(LOC_PLANET, $planet);
0 ignored issues
show
Bug introduced by
The method db_ins_record does only exist in SnDbCachedOperator, but not in Closure.

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

Let’s take a look at an example:

class A
{
    public function foo() { }
}

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

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

Available Fixes

  1. Add an additional type-check:

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

    function someFunction(B $x) { /** ... */ }
    
Loading history...
126
127
  return !empty($RetValue['id']) ? $RetValue['id'] : false; // OK
128
}
129
130
/**
131
 * uni_create_moon.php
132
 *
133
 * UNI: Create moon record
134
 *
135
 * V2.1  - copyright (c) 2010-2011 by Gorlum for http://supernova.ws
136
 *   [~] Renamed CreateOneMoonRecord to uni_create_moon
137
 *   [-] Removed unsed $MoonID parameter from call
138
 *   [~] PCG1 compliant
139
 * V2.0  - copyright (c) 2010 by Gorlum for http://supernova.ws
140
 *   [+] Deep rewrite to rid of using `galaxy` and `lunas` tables greatly reduce numbers of SQL-queries
141
 * @version 1.1
142
 * @copyright 2008
143
 */
144
145
/**
146
 * @param        $pos_galaxy
147
 * @param        $pos_system
148
 * @param        $pos_planet
149
 * @param        $user_id
150
 * @param int    $moon_chance
151
 * <p><b>0</b> случайный размер луны</p>
152
 * <p>1..100 Шанс выпадения луны</p>
153
 * <p>> 100 Размер луны</p>
154
 * @param string $moon_name
155
 * @param bool   $update_debris
156
 * @param array  $options
157
 *
158
 * @return array|false|resource
159
 */
160
function uni_create_moon($pos_galaxy, $pos_system, $pos_planet, $user_id, $moon_chance = 0, $moon_name = '', $update_debris = true, $options = array()) {
0 ignored issues
show
Unused Code introduced by
The parameter $moon_name 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...
161
  $classLocale = classLocale::$lang;
162
163
  $moon_name = '';
164
  $moon_row = array();
165
  $moon = DBStaticPlanet::db_planet_by_gspt($pos_galaxy, $pos_system, $pos_planet, PT_MOON, false, 'id');
166
  if(!$moon['id']) {
167
    $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`');
168
169
    if($moon_planet['id']) {
170
      $base_storage_size = BASE_STORAGE_SIZE;
171
172
      if(!$moon_chance) {
173
        $size = mt_rand(1100, 8999);
174
      } elseif($moon_chance <= 100) {
175
        $size = mt_rand($moon_chance * 100 + 1000, $moon_chance * 200 + 2999);
176
      } else {
177
        $size = $moon_chance;
178
      }
179
180
      $moon_chance = min(30, ceil($size / 1000));
181
182
      $temp_min = $moon_planet['temp_min'] - rand(10, 45);
183
      $temp_max = $temp_min + 40;
184
185
      $moon_name = $moon_name ? $moon_name : "{$moon_planet['name']} {$classLocale['sys_moon']}";
186
187
      $field_max = ceil($size / 1000);
188
189
      if(isset($options['image']) && $options['image']) {
190
        $moon_image = $options['image'];
191
      } else {
192
        $moon_image = 'mond';
193
      }
194
195
      $moon_row = classSupernova::$gc->cacheOperator->db_ins_record(LOC_PLANET, array(
0 ignored issues
show
Bug introduced by
The method db_ins_record does only exist in SnDbCachedOperator, but not in Closure.

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

Let’s take a look at an example:

class A
{
    public function foo() { }
}

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

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

Available Fixes

  1. Add an additional type-check:

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

    function someFunction(B $x) { /** ... */ }
    
Loading history...
196
        'id_owner'          => $user_id,
197
        'parent_planet'     => $moon_planet['id'],
198
        'name'              => $moon_name,
199
        'last_update'       => SN_TIME_NOW,
200
        'image'             => $moon_image,
201
        'galaxy'            => $pos_galaxy,
202
        'system'            => $pos_system,
203
        'planet'            => $pos_planet,
204
        'planet_type'       => PT_MOON,
205
        'diameter'          => $size,
206
        'field_max'         => $field_max,
207
        'density'           => 2500,
208
        'density_index'     => 2,
209
        'temp_min'          => $temp_min,
210
        'temp_max'          => $temp_max,
211
        'metal'             => 0,
212
        'metal_perhour'     => 0,
213
        'metal_max'         => $base_storage_size,
214
        'crystal'           => 0,
215
        'crystal_perhour'   => 0,
216
        'crystal_max'       => $base_storage_size,
217
        'deuterium'         => 0,
218
        'deuterium_perhour' => 0,
219
        'deuterium_max'     => $base_storage_size,
220
      ));
221
222
      if($update_debris) {
223
        $debris_spent = $moon_chance * 1000000;
224
        $metal_spent = round(min($moon_planet['debris_metal'], $debris_spent * mt_rand(50, 75) / 100));
225
        $crystal_spent = min($moon_planet['debris_crystal'], $debris_spent - $metal_spent);
226
        $metal_spent = min($moon_planet['debris_metal'], $debris_spent - $crystal_spent); // Need if crystal less then their part
227
        DBStaticPlanet::db_planet_update_set_by_id($moon_planet['id'], "`debris_metal` = GREATEST(0, `debris_metal` - {$metal_spent}), `debris_crystal` = GREATEST(0, `debris_crystal` - {$crystal_spent})");
228
      }
229
    }
230
  }
231
232
  return $moon_row;
233
}
234
235
/*
236
 *
237
 * @function SetSelectedPlanet
238
 *
239
 * @history
240
 *
241
 * 4 - copyright (c) 2014 by Gorlum for http://supernova.ws
242
 *   [!] Full rewrote from scratch
243
 * 3 - copyright (c) 2009-2011 by Gorlum for http://supernova.ws
244
 *   [+] Added handling case when current_planet does not exists or didn't belong to user
245
 *   [+] Moved from SetSelectedPlanet.php
246
 *   [+] Function now return
247
 *   [~] Complies with PCG1
248
 * 2 - copyright (c) 2009-2011 by Gorlum for http://supernova.ws
249
 *   [~] Security checked for SQL-injection
250
 * 1 - copyright 2008 By Chlorel for XNova
251
 *
252
 */
253
function SetSelectedPlanet(&$user) {
254
  $planet_row['id'] = $user['current_planet'];
0 ignored issues
show
Coding Style Comprehensibility 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.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
255
256
  // Пытаемся переключить на новую планету
257
  if(($selected_planet = sys_get_param_id('cp')) && $selected_planet != $user['current_planet']) {
258
    $planet_row = DBStaticPlanet::db_planet_by_id_and_owner($selected_planet, $user['id'], false, 'id');
259
  } else {
260
    $planet_row = DBStaticPlanet::db_planet_by_id($planet_row['id']);
261
  }
262
263
  // Если новая планета не найдена или было переключения - проверяем текущую выбранную планету
264
  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...
265
  {
266
    $planet_row = DBStaticPlanet::db_planet_by_id_and_owner($user['current_planet'], $user['id'], false, 'id');
267
    // Если текущей планеты не существует - выставляем Столицу
268
    if(!isset($planet_row['id'])) {
269
      $planet_row = DBStaticPlanet::db_planet_by_id_and_owner($user['id_planet'], $user['id'], false, 'id');
270
      // Если и столицы не существует - значит что-то очень не так с записью пользователя
271
      if(!isset($planet_row['id'])) {
272
        classSupernova::$debug->error("User ID {$user['id']} has Capital planet {$user['id_planet']} but this planet does not exists", 'User record error', 502);
273
      }
274
    }
275
  }
276
277
  // Если производилось переключение планеты - делаем запись в юзере
278
  if($user['current_planet'] != $planet_row['id']) {
279
    DBStaticUser::db_user_set_by_id($user['id'], "`current_planet` = '{$planet_row['id']}'");
280
    $user['current_planet'] = $planet_row['id'];
281
  }
282
283
  return $user['current_planet'];
284
}
285
286
/**
287
 * @param Vector $vector
288
 */
289
function uniRenderVector($vector) {
290
  return "[{$vector->galaxy}:{$vector->system}:{$vector->planet}]";
291
}
292
293
// ----------------------------------------------------------------------------------------------------------------
294
function uni_render_coordinates($from, $prefix = '') {
295
  return "[{$from[$prefix . 'galaxy']}:{$from[$prefix . 'system']}:{$from[$prefix . 'planet']}]";
296
}
297
298
function uni_render_planet($from) {
299
  return "[{$from['galaxy']}:{$from['system']}:{$from['planet']}] {$from['name']}";
300
}
301
302
function uni_render_planet_full($from, $prefix = '', $html_safe = true, $include_id = false) {
303
  if(!$from['id']) {
304
    $result = classLocale::$lang['sys_planet_expedition'];
305
  } else {
306
    $from_planet_id = $include_id ? (
307
      'ID {' . ($from['id'] ? $from['id'] : ($from[$prefix . 'planet_id'] ? $from[$prefix . 'planet_id'] : 0)) . '} '
308
    ) : '';
309
310
    $from_planet_type = $from['planet_type'] ? $from['planet_type'] : ($from[$prefix . 'type'] ? $from[$prefix . 'type'] : 0);
311
    $from_planet_type = ($from_planet_type ? ' ' . classLocale::$lang['sys_planet_type_sh'][$from_planet_type] : '');
312
313
    $result = $from_planet_id . uni_render_coordinates($from, $prefix) . $from_planet_type . ($from['name'] ? ' ' . $from['name'] : '');
314
    $result = $html_safe ? str_replace(' ', '&nbsp;', htmlentities($result, ENT_COMPAT, 'UTF-8')) : $result;
315
  }
316
317
  return $result;
318
}
319
320
function uni_render_coordinates_url($from, $prefix = '', $page = 'galaxy.php') {
321
  return $page . (strpos($page, '?') === false ? '?' : '&') . "galaxy={$from[$prefix . 'galaxy']}&system={$from[$prefix . 'system']}&planet={$from[$prefix . 'planet']}";
322
}
323
324
function uni_render_coordinates_href($from, $prefix = '', $mode = 0, $fleet_type = '') {
325
  return '<a href="' . uni_render_coordinates_url($from, $prefix, "galaxy.php?mode={$mode}") . '"' . ($fleet_type ? " {$fleet_type}" : '') . '>' . uni_render_coordinates($from, $prefix) . '</a>';
326
}
327
328
function uni_get_time_to_jump($moon_row) {
329
  $jump_gate_level = mrc_get_level($user, $moon_row, STRUC_MOON_GATE);
330
331
  return $jump_gate_level ? max(0, $moon_row['last_jump_time'] + abs(60 * 60 / $jump_gate_level) - SN_TIME_NOW) : 0;
332
}
333
334
function uni_calculate_moon_chance($FleetDebris) {
335
  $MoonChance = $FleetDebris / 1000000;
336
337
  return ($MoonChance < 1) ? 0 : ($MoonChance > 30 ? 30 : $MoonChance);
338
}
339
340
/**
341
 * @param array  $coordinates
342
 * @param string $prefix
343
 *
344
 * @return bool
345
 */
346
function uni_coordinates_valid($coordinates, $prefix = '') {
347
  // 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...
348
  $coordinates["{$prefix}galaxy"] = intval($coordinates["{$prefix}galaxy"]);
349
  $coordinates["{$prefix}system"] = intval($coordinates["{$prefix}system"]);
350
  $coordinates["{$prefix}planet"] = intval($coordinates["{$prefix}planet"]);
351
352
  return
353
    isset($coordinates["{$prefix}galaxy"]) && $coordinates["{$prefix}galaxy"] > 0 && $coordinates["{$prefix}galaxy"] <= Vector::$knownGalaxies&&
354
    isset($coordinates["{$prefix}system"]) && $coordinates["{$prefix}system"] > 0 && $coordinates["{$prefix}system"] <= Vector::$knownSystems&&
355
    isset($coordinates["{$prefix}planet"]) && $coordinates["{$prefix}planet"] > 0 && $coordinates["{$prefix}planet"] <= Vector::$knownPlanets;
356
}
357
358
function uni_planet_teleport_check($user, $planetrow, $new_coordinates = null) {
359
  try {
360
    if($planetrow['planet_teleport_next'] && $planetrow['planet_teleport_next'] > SN_TIME_NOW) {
361
      throw new exception(classLocale::$lang['ov_teleport_err_cooldown'], ERR_ERROR);
362
    }
363
364
    if(mrc_get_level($user, null, RES_DARK_MATTER) < classSupernova::$config->planet_teleport_cost) {
365
      throw new exception(classLocale::$lang['ov_teleport_err_no_dark_matter'], ERR_ERROR);
366
    }
367
368
    // TODO: Replace quick-check with using gathered flying fleet data
369
    if(FleetList::fleet_count_incoming($planetrow['galaxy'], $planetrow['system'], $planetrow['planet'])) {
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...
370
      throw new exception(classLocale::$lang['ov_teleport_err_fleet'], ERR_ERROR);
371
    }
372
373
    if(is_array($new_coordinates)) {
374
      $new_coordinates['planet_type'] = PT_PLANET;
375
      $incoming = DBStaticPlanet::db_planet_by_vector($new_coordinates, '', true, 'id');
376
      if($incoming['id']) {
377
        throw new exception(classLocale::$lang['ov_teleport_err_destination_busy'], ERR_ERROR);
378
      }
379
    }
380
381
    $response = array(
382
      'result'  => ERR_NONE,
383
      'message' => '',
384
    );
385
  } catch(exception $e) {
386
    $response = array(
387
      'result'  => $e->getCode(),
388
      'message' => $e->getMessage(),
389
    );
390
  }
391
392
  return $response;
393
}
394