Passed
Branch trunk (7dc288)
by SuperNova.WS
06:07
created

PageOverview   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 436
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 436
ccs 0
cts 302
cp 0
rs 6
c 0
b 0
f 0
wmc 55

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getPlanet() 0 6 2
A __construct() 0 9 1
B templateGridSizes() 0 18 5
F manage() 0 153 24
A setPlanetById() 0 2 1
F overview() 0 135 15
A templateSector() 0 16 2
A route() 0 13 2
A templateQue() 0 16 3

How to fix   Complexity   

Complex Class

Complex classes like PageOverview 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.

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 PageOverview, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Created by Gorlum 25.01.2018 7:50
4
 */
5
6
namespace Deprecated;
7
8
use DBStaticPlanet;
9
use classSupernova;
10
use HelperString;
11
use Exception;
12
use Planet\Planet;
13
use template;
14
15
class PageOverview extends PageDeprecated {
16
  /**
17
   * @var \classConfig $config
18
   */
19
  protected $config;
20
  /**
21
   * @var \core_auth $auth
22
   */
23
  protected $auth;
24
  /**
25
   * @var \classLocale $lang
26
   */
27
  protected $lang;
28
29
  /**
30
   * @var Planet $planet
31
   */
32
  protected $planet;
33
34
  public function __construct() {
35
    parent::__construct();
36
37
    $this->lang = classSupernova::$lang;
38
    $this->config = classSupernova::$config;
39
    $this->auth = classSupernova::$auth;
40
41
    lng_include('overview');
42
    lng_include('mrc_mercenary');
43
  }
44
45
  public function setPlanetById($planetId) {
46
    $this->planet = new Planet($planetId);
47
  }
48
49
  public function getPlanet() {
50
    if (empty($this->planet)) {
51
      throw new Exception('No planet in Overview');
52
    }
53
54
    return $this->planet;
55
  }
56
57
  public function route() {
58
    global $user, $planetrow, $que, $user_option_list;
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
    $this->setPlanetById($planetrow['id']);
61
62
    switch ($mode = sys_get_param_str('mode')) {
63
      case 'manage':
64
        $this->manage($user, $planetrow);
65
      break;
66
67
      default:
68
        $this->overview($user, $planetrow, $que, $user_option_list);
69
      break;
70
    }
71
  }
72
73
  /**
74
   * @param $user
75
   * @param $planetrow
76
   * @param $que
77
   * @param $user_option_list
78
   */
79
  public function overview($user, $planetrow, $que, $user_option_list) {
80
    $this->setPlanetById($planetrow['id']);
81
82
    $this->planet->sn_sys_sector_buy();
83
84
    rpg_level_up($user, RPG_STRUCTURE);
85
    rpg_level_up($user, RPG_RAID);
86
    rpg_level_up($user, RPG_TECH);
87
    rpg_level_up($user, RPG_EXPLORE);
88
89
    if (sys_get_param_str('rename') && $new_name = sys_get_param_str('new_name')) {
90
      $planetrow['name'] = $new_name;
91
      $new_name_safe = db_escape($new_name);
92
      DBStaticPlanet::db_planet_set_by_id($planetrow['id'], "`name` = '{$new_name_safe}'");
93
    }
94
95
    if (!empty($theResult = $this->planet->sn_sys_planet_core_transmute($user))) {
96
      $this->resultMessageList->add($theResult['MESSAGE'], $theResult['STATUS']);
97
    }
98
99
    $template = gettemplate('planet_overview', true);
100
101
    $user_dark_matter = mrc_get_level($user, false, RES_DARK_MATTER);
102
    $template->assign_recursive($this->planet->tpl_planet_density_info($user_dark_matter));
103
104
    $planet_count = 0;
105
    $planets_query = DBStaticPlanet::db_planet_list_sorted($user, false, '*');
106
    foreach ($planets_query as $an_id => $planetRecord) {
107
      sn_db_transaction_start();
108
      $updatedData = sys_o_get_updated($user, $planetRecord['id'], SN_TIME_NOW, false, true);
109
      sn_db_transaction_commit();
110
111
      $fleets_to_planet = null;
112
      $templatizedPlanet = tpl_parse_planet($updatedData['planet'], $fleets_to_planet);
113
114
      if ($planetRecord['planet_type'] == PT_MOON) {
115
        continue;
116
      }
117
      $moon = DBStaticPlanet::db_planet_by_parent($planetRecord['id']);
118
      if ($moon) {
119
        $moon_fill = min(100, floor($moon['field_current'] / eco_planet_fields_max($moon) * 100));
120
      } else {
121
        $moon_fill = 0;
122
      }
123
124
      $moon_fleets = flt_get_fleets_to_planet($moon);
125
      $template->assign_block_vars('planet', array_merge($templatizedPlanet, array(
126
        'MOON_ID'    => $moon['id'],
127
        'MOON_NAME'  => $moon['name'],
128
        'MOON_IMG'   => $moon['image'],
129
        'MOON_FILL'  => min(100, $moon_fill),
130
        'MOON_ENEMY' => $moon_fleets['enemy']['count'],
131
132
        'MOON_PLANET' => $moon['parent_planet'],
133
      )));
134
135
      $planet_count++;
136
    }
137
138
    $fleets = flt_parse_fleets_to_events(fleet_and_missiles_list_incoming($user['id']));
139
    tpl_assign_fleet($template, $fleets_to_planet);
140
    tpl_assign_fleet($template, $fleets);
141
142
    $lune = $planetrow['planet_type'] == PT_PLANET ? DBStaticPlanet::db_planet_by_parent($planetrow['id']) : DBStaticPlanet::db_planet_by_id($planetrow['parent_planet']);
143
    if ($lune) {
144
      $template->assign_vars([
145
        'MOON_ID'   => $lune['id'],
146
        'MOON_IMG'  => $lune['image'],
147
        'MOON_NAME' => $lune['name'],
148
      ]);
149
    }
150
151
    $template->assign_recursive($this->planet->int_planet_pretemplate($user));
152
153
    if (!defined('GAME_STRUCTURES_DISABLED') || !GAME_STRUCTURES_DISABLED) {
154
      $this->templateQue($template, QUE_STRUCTURES, $que);
155
    }
156
157
    $this->templateQue($template, SUBQUE_FLEET, $que);
158
    if (!defined('GAME_DEFENSE_DISABLED') || !GAME_DEFENSE_DISABLED) {
159
      $this->templateQue($template, SUBQUE_DEFENSE, $que);
160
    }
161
162
    $template->assign_vars($this->templateGridSizes($user, $user_option_list, $planet_count));
163
164
    $template->assign_vars($this->templateSector($user, $user_dark_matter));
165
166
    $planet_recyclers_orbiting = 0;
167
    foreach (sn_get_groups('flt_recyclers') as $recycler_id) {
168
      $planet_recyclers_orbiting += mrc_get_level($user, $planetrow, $recycler_id);
169
    }
170
    $governor_level = $planetrow['PLANET_GOVERNOR_ID'] ? mrc_get_level($user, $planetrow, $planetrow['PLANET_GOVERNOR_ID'], false, true) : 0;
171
    $template->assign_vars([
172
      'USER_ID'        => $user['id'],
173
      'user_username'  => $user['username'],
174
      'USER_AUTHLEVEL' => $user['authlevel'],
175
176
      'NEW_MESSAGES' => $user['new_message'],
177
      // TODO
178
      // 'NEW_LEVEL_MINER' => $level_miner,
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
179
      // 'NEW_LEVEL_RAID'  => $level_raid,
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
180
181
      'planet_diameter' => HelperString::numberFloorAndFormat($planetrow['diameter']),
182
183
      'metal_debris'         => HelperString::numberFloorAndFormat($planetrow['debris_metal']),
184
      'crystal_debris'       => HelperString::numberFloorAndFormat($planetrow['debris_crystal']),
185
      'PLANET_RECYCLERS'     => $planet_recyclers_orbiting,
186
      'planet_image'         => $planetrow['image'],
187
      'planet_temp_min'      => $planetrow['temp_min'],
188
      'planet_temp_avg'      => round(($planetrow['temp_min'] + $planetrow['temp_max']) / 2),
189
      'planet_temp_max'      => $planetrow['temp_max'],
190
      'planet_density'       => $planetrow['density'],
191
      'planet_density_index' => $planetrow['density_index'],
192
      'planet_density_text'  => $this->lang['uni_planet_density_types'][$planetrow['density_index']],
193
194
      'GATE_LEVEL'          => mrc_get_level($user, $planetrow, STRUC_MOON_GATE),
195
      'GATE_JUMP_REST_TIME' => uni_get_time_to_jump($planetrow),
196
197
      'ADMIN_EMAIL' => $this->config->game_adminEmail,
198
199
      'PLANET_GOVERNOR_ID'         => $planetrow['PLANET_GOVERNOR_ID'],
200
      'PLANET_GOVERNOR_LEVEL'      => $governor_level,
201
      'PLANET_GOVERNOR_LEVEL_PLUS' => mrc_get_level($user, $planetrow, $planetrow['PLANET_GOVERNOR_ID']) - $governor_level,
202
      'PLANET_GOVERNOR_NAME'       => $this->lang['tech'][$planetrow['PLANET_GOVERNOR_ID']],
203
204
205
      'DARK_MATTER' => $user_dark_matter,
206
207
      'PAGE_HEADER' => $this->lang['ov_overview'] . " - " . $this->lang['sys_planet_type'][$planetrow['planet_type']] . " {$planetrow['name']} [{$planetrow['galaxy']}:{$planetrow['system']}:{$planetrow['planet']}]",
208
    ]);
209
    tpl_set_resource_info($template, $planetrow, $fleets_to_planet);
210
211
    $this->resultMessageList->templateAdd($template);
212
213
    display($template);
214
  }
215
216
  /**
217
   * @param $user
218
   * @param $planetrow
219
   */
220
  public function manage($user, $planetrow) {
221
    $this->setPlanetById($planetrow['id']);
222
223
    $this->planet->sn_sys_sector_buy('overview.php?mode=manage');
224
225
    $user_dark_matter = mrc_get_level($user, false, RES_DARK_MATTER);
226
    if (!empty($theResult = $this->planet->sn_sys_planet_core_transmute($user))) {
227
      $this->resultMessageList->add($theResult['MESSAGE'], $theResult['STATUS']);
228
    }
229
230
    $template = gettemplate('planet_manage', true);
231
    $planet_id = sys_get_param_id('planet_id');
232
233
    if (sys_get_param_str('rename') && $new_name = sys_get_param_str('new_name')) {
234
      $planetrow['name'] = $new_name;
235
      DBStaticPlanet::db_planet_set_by_id($planetrow['id'], "`name` = '{$new_name}'");
236
    } elseif (sys_get_param_str('action') == 'make_capital') {
237
      try {
238
        sn_db_transaction_start();
239
        $user = db_user_by_id($user['id'], true, '*');
240
        $planetrow = DBStaticPlanet::db_planet_by_id($planetrow['id'], true, '*');
241
242
        if ($planetrow['planet_type'] != PT_PLANET) {
243
          throw new exception($this->lang['ov_capital_err_not_a_planet'], ERR_ERROR);
244
        }
245
246
        if ($planetrow['id'] == $user['id_planet']) {
247
          throw new exception($this->lang['ov_capital_err_capital_already'], ERR_ERROR);
248
        }
249
250
        if ($user_dark_matter < $this->config->planet_capital_cost) {
251
          throw new exception($this->lang['ov_capital_err_no_dark_matter'], ERR_ERROR);
252
        }
253
254
        rpg_points_change($user['id'], RPG_CAPITAL, -$this->config->planet_capital_cost,
255
          array('Planet %s ID %d at coordinates %s now become Empire Capital', $planetrow['name'], $planetrow['id'], uni_render_coordinates($planetrow))
256
        );
257
258
        db_user_set_by_id($user['id'], "id_planet = {$planetrow['id']}, galaxy = {$planetrow['galaxy']}, system = {$planetrow['system']}, planet = {$planetrow['planet']}");
259
260
        $user['id_planet'] = $planetrow['id'];
261
        $this->resultMessageList->add($this->lang['ov_capital_err_none'], ERR_NONE);
262
        sn_db_transaction_commit();
263
        sys_redirect('overview.php?mode=manage');
264
      } catch (exception $e) {
265
        sn_db_transaction_rollback();
266
        $this->resultMessageList->add($e->getMessage(), $e->getCode());
267
      }
268
    } elseif (sys_get_param_str('action') == 'planet_teleport') {
269
      try {
270
        if (!uni_coordinates_valid($new_coordinates = array(
271
          'galaxy' => sys_get_param_int('new_galaxy'),
272
          'system' => sys_get_param_int('new_system'),
273
          'planet' => sys_get_param_int('new_planet')))
274
        ) {
275
          throw new exception($this->lang['ov_teleport_err_wrong_coordinates'], ERR_ERROR);
276
        }
277
278
        sn_db_transaction_start();
279
        // При телепорте обновлять данные не надо - просто получить текущие данные и залочить их
280
        $user = db_user_by_id($user['id'], true, '*');
281
        $planetrow = DBStaticPlanet::db_planet_by_id($planetrow['id'], true, '*');
282
283
        $can_teleport = uni_planet_teleport_check($user, $planetrow, $new_coordinates);
284
        if ($can_teleport['result'] != ERR_NONE) {
285
          throw new exception($can_teleport['message'], $can_teleport['result']);
286
        }
287
288
        rpg_points_change($user['id'], RPG_TELEPORT, -$this->config->planet_teleport_cost,
289
          array($this->lang['ov_teleport_log_record'], $planetrow['name'], $planetrow['id'], uni_render_coordinates($planetrow), uni_render_coordinates($new_coordinates))
290
        );
291
        $planet_teleport_next = SN_TIME_NOW + $this->config->planet_teleport_timeout;
292
        DBStaticPlanet::db_planet_set_by_gspt($planetrow['galaxy'], $planetrow['system'], $planetrow['planet'], PT_ALL,
293
          "galaxy = {$new_coordinates['galaxy']}, system = {$new_coordinates['system']}, planet = {$new_coordinates['planet']}, planet_teleport_next = {$planet_teleport_next}");
294
295
        if ($planetrow['id'] == $user['id_planet']) {
296
          db_user_set_by_id($user['id'], "galaxy = {$new_coordinates['galaxy']}, system = {$new_coordinates['system']}, planet = {$new_coordinates['planet']}");
297
        }
298
        sn_db_transaction_commit();
299
300
        $user = db_user_by_id($user['id'], true, '*');
301
        $planetrow = DBStaticPlanet::db_planet_by_id($planetrow['id'], true, '*');
302
        $this->resultMessageList->add($this->lang['ov_teleport_err_none'], ERR_NONE);
303
        sys_redirect('overview.php?mode=manage');
304
      } catch (exception $e) {
305
        sn_db_transaction_rollback();
306
        $this->resultMessageList->add($e->getMessage(), $e->getCode());
307
      }
308
    } elseif (sys_get_param_str('action') == 'planet_abandon') {
309
      if ($this->auth->password_check(sys_get_param('abandon_confirm'))) {
310
        if ($user['id_planet'] != $user['current_planet'] && $user['current_planet'] == $planet_id) {
311
          $destroyed = SN_TIME_NOW + 60 * 60 * 24;
312
          DBStaticPlanet::db_planet_set_by_id($user['current_planet'], "`destruyed`='{$destroyed}', `id_owner`=0");
313
          DBStaticPlanet::db_planet_set_by_parent($user['current_planet'], "`destruyed`='{$destroyed}', `id_owner`=0");
314
          db_user_set_by_id($user['id'], '`current_planet` = `id_planet`');
315
          messageBox($this->lang['ov_delete_ok'], $this->lang['colony_abandon'], 'overview.php?mode=manage');
316
        } else {
317
          messageBox($this->lang['ov_delete_wrong_planet'], $this->lang['colony_abandon'], 'overview.php?mode=manage');
318
        }
319
      } else {
320
        messageBox($this->lang['ov_delete_wrong_pass'], $this->lang['colony_abandon'], 'overview.php?mode=manage');
321
      }
322
    } elseif (($hire = sys_get_param_int('hire')) && in_array($hire, sn_get_groups('governors'))) {
323
      $this->planet->governorHire($hire);
324
325
      sys_redirect('overview.php?mode=manage');
326
      die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
327
    }
328
329
    // TODO - refresh planet by itself
330
    $this->setPlanetById($planetrow['id']);
331
    $template->assign_recursive($this->planet->int_planet_pretemplate($user));
332
333
    foreach (sn_get_groups('governors') as $governor_id) {
334
      if ($planetrow['planet_type'] == PT_MOON && $governor_id == MRC_TECHNOLOGIST) {
335
        continue;
336
      }
337
338
      $governor_level = $planetrow['PLANET_GOVERNOR_ID'] == $governor_id ? $planetrow['PLANET_GOVERNOR_LEVEL'] : 0;
339
      $build_data = eco_get_build_data($user, $planetrow, $governor_id, $governor_level);
340
      $template->assign_block_vars('governors', array(
341
        'ID'         => $governor_id,
342
        'NAME'       => $this->lang['tech'][$governor_id],
343
        'COST'       => $build_data[BUILD_CREATE][RES_DARK_MATTER],
344
        'MAX'        => get_unit_param($governor_id, P_MAX_STACK),
345
        'LEVEL'      => $governor_level,
346
        'LEVEL_PLUS' => mrc_get_level($user, $planetrow, $governor_id) - $governor_level,
347
      ));
348
    }
349
350
    $user_dark_matter = mrc_get_level($user, false, RES_DARK_MATTER);
351
    $template->assign_recursive($this->planet->tpl_planet_density_info($user_dark_matter));
352
353
    $template->assign_vars($this->templateSector($user, $user_dark_matter));
354
355
    $can_teleport = uni_planet_teleport_check($user, $planetrow);
356
    $template->assign_vars(array(
357
      'DARK_MATTER' => $user_dark_matter,
358
359
      'CAN_TELEPORT'         => $can_teleport['result'] == ERR_NONE,
360
      'CAN_NOT_TELEPORT_MSG' => $can_teleport['message'],
361
      'TELEPORT_COST_TEXT'   => prettyNumberStyledCompare($this->config->planet_teleport_cost, $user_dark_matter),
362
363
      'IS_CAPITAL'        => $planetrow['id'] == $user['id_planet'],
364
      'CAN_CAPITAL'       => $user_dark_matter >= $this->config->planet_capital_cost,
365
      'CAPITAL_COST_TEXT' => prettyNumberStyledCompare($this->config->planet_capital_cost, $user_dark_matter),
366
367
      'PAGE_HINT' => $this->lang['ov_manage_page_hint'],
368
    ));
369
370
    $this->resultMessageList->templateAdd($template);
371
372
    display($template, $this->lang['rename_and_abandon_planet']);
373
  }
374
375
  /**
376
   * @param $user
377
   * @param $user_dark_matter
378
   *
379
   * @return array
380
   */
381
  protected function templateSector($user, $user_dark_matter) {
382
    $sector_cost = eco_get_build_data($user, $this->planet->asArray(), UNIT_SECTOR, mrc_get_level($user, $this->planet->asArray(), UNIT_SECTOR), true);
383
    $sector_cost = $sector_cost[BUILD_CREATE][RES_DARK_MATTER];
384
    $planet_fill = floor($this->planet->field_current / eco_planet_fields_max($this->planet->asArray()) * 100);
385
    $planet_fill = $planet_fill > 100 ? 100 : $planet_fill;
386
    $vararray = [
387
      'planet_field_current' => $this->planet->field_current,
388
      'planet_field_max'     => eco_planet_fields_max($this->planet->asArray()),
389
      'PLANET_FILL'          => floor($this->planet->field_current / eco_planet_fields_max($this->planet->asArray()) * 100),
390
      'PLANET_FILL_BAR'      => $planet_fill,
391
      'SECTOR_CAN_BUY'       => $sector_cost <= $user_dark_matter,
392
      'SECTOR_COST'          => $sector_cost,
393
      'SECTOR_COST_TEXT'     => HelperString::numberFloorAndFormat($sector_cost),
394
    ];
395
396
    return $vararray;
397
  }
398
399
400
  /**
401
   * @param template $template
402
   * @param int      $que_type
403
   * @param          $que
404
   */
405
  protected function templateQue($template, $que_type, $que) {
406
//    $que = que_get($planet->id_owner, $planet->id, $que_type);
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
407
    $que = $que['ques'][$que_type][$this->planet->id_owner][$this->planet->id];
408
409
    $que_length = 0;
410
    if (!empty($que)) {
411
      foreach ($que as $que_item) {
412
        $template->assign_block_vars('que', que_tpl_parse_element($que_item));
413
      }
414
      $que_length = count($que);
415
    }
416
417
    $template->assign_block_vars('ques', [
418
      'ID'     => $que_type,
419
      'NAME'   => $this->lang['sys_ques'][$que_type],
420
      'LENGTH' => $que_length,
421
    ]);
422
  }
423
424
  /**
425
   * Calculates planet grid sizes (horizontal and vertical) for Planet Overview
426
   *
427
   * @param $user
428
   * @param $user_option_list
429
   * @param $planet_count
430
   *
431
   * @return array
432
   */
433
  protected function templateGridSizes($user, $user_option_list, $planet_count) {
434
    $overview_planet_rows = $user['opt_int_overview_planet_rows'];
435
    $overview_planet_columns = $user['opt_int_overview_planet_columns'];
436
437
    if ($overview_planet_rows <= 0 && $overview_planet_columns <= 0) {
438
      $overview_planet_rows = $user_option_list[OPT_INTERFACE]['opt_int_overview_planet_rows'];
439
      $overview_planet_columns = $user_option_list[OPT_INTERFACE]['opt_int_overview_planet_columns'];
440
    }
441
442
    if ($overview_planet_rows > 0 && $overview_planet_columns <= 0) {
443
      $overview_planet_columns = ceil($planet_count / $overview_planet_rows);
444
    }
445
    $vararray = [
446
      'LIST_ROW_COUNT'    => $overview_planet_rows,
447
      'LIST_COLUMN_COUNT' => $overview_planet_columns,
448
    ];
449
450
    return $vararray;
451
  }
452
453
}
454