Completed
Push — work-fleets ( fff2b6...e0e753 )
by SuperNova.WS
06:54
created

imperium.php ➔ sn_imperium_view()   F

Complexity

Conditions 38
Paths 11520

Size

Total Lines 252
Code Lines 160

Duplication

Lines 6
Ratio 2.38 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 38
eloc 160
nc 11520
nop 1
dl 6
loc 252
rs 2
c 2
b 0
f 0

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
// TODO: Переделать под $template_result
4
5
/*
6
 * imperium.php
7
 *
8
 * Overview you empire
9
 *
10
 * @version 2.1 copyright (c) 2010-2012 by Gorlum for http://supernova.ws
11
 *
12
 */
13
14
classSupernova::$sn_mvc['view']['imperium'][] = 'sn_imperium_view';
15
16
function sn_imperium_view($template = null) {
17
  global $user;
18
19
  $planets = array();
20
  $ques = array();
21
22
  $sn_group_factories = sn_get_groups('factories');
23
  $planet_density = sn_get_groups('planet_density');
24
25
  if(sys_get_param('save_production')) {
26
    $production = sys_get_param('percent');
27
    if(is_array($production) && !empty($production)) {
28
      // sn_db_transaction_start();
29
      $query = array();
30
      $planet_row_list = db_planet_list_sorted($user, false, '*');
31
      // while($planet = db_fetch($planet_row_list))
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...
32
      foreach($planet_row_list as $planet) {
33
        foreach($sn_group_factories as $factory_unit_id) {
34
          $unit_db_name_porcent = pname_factory_production_field_name($factory_unit_id);
35
          if(
36
            get_unit_param($factory_unit_id, P_MINING_IS_MANAGED)
37
            && isset($production[$factory_unit_id][$planet['id']])
38
            && ($actual_porcent = intval($production[$factory_unit_id][$planet['id']] / 10)) >= 0
39
            && $actual_porcent <= 10
40
            && $actual_porcent != $planet[$unit_db_name_porcent]
41
          ) {
42
            $query[$planet['id']][] = "{$unit_db_name_porcent} = {$actual_porcent}";
43
          }
44
        }
45
      }
46
      foreach($query as $planet_id => $query_data) {
47
        db_planet_set_by_id($planet_id, implode(',', $query_data));
48
      }
49
      // sn_db_transaction_commit();
50
    }
51
  }
52
53
  $planet_row_list = db_planet_list_sorted($user);
54
  // while ($planet = db_fetch($planet_row_list))
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
55
  foreach($planet_row_list as $planet) {
56
    sn_db_transaction_start();
57
    $global_data = sys_o_get_updated($user, $planet['id'], SN_TIME_NOW, false, true);
58
    $planets[$planet['id']] = $global_data['planet'];
59
    // $ques[$planet['id']] = que_get($user['id'], $planet['id'], false);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
60
    $ques[$planet['id']] = $global_data['que'];
61
    sn_db_transaction_commit();
62
  }
63
64
  $template = gettemplate('imperium', $template);
65
  $template->assign_var('amount', count($planets) + 2);
66
67
  for($i = 100; $i >= 0; $i -= 10) {
68
    $template->assign_block_vars('percent', array('PERCENT' => $i));
69
  }
70
71
  $fleet_id = 1;
72
  $fleets = array();
73
74
  $total['temp_min'] = 1000;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$total was never initialized. Although not strictly required by PHP, it is generally a good practice to add $total = 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...
75
  $total['temp_max'] = -999;
76
77
  foreach($planets as $planet_index => &$planet) {
78
    $list_planet_que = $ques[$planet_index];
79
    $planet_template = tpl_parse_planet($planet);
80
81
    $planet_fleet_id = 0;
82
    $fleet_list = $planet_template['fleet_list'];//flt_get_fleets_to_planet($planet);
83 View Code Duplication
    if($fleet_list['own']['count']) {
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...
84
      $planet_fleet_id = "p{$fleet_id}";
85
      $fleets[] = tpl_parse_fleet_sn($fleet_list['own']['total'], $planet_fleet_id);
86
      $fleet_id++;
87
    }
88
89
    $template->assign_block_vars('planet', array_merge($planet_template, array(
90
      'PLANET_FLEET_ID' => $planet_fleet_id,
91
92
      'METAL_CUR'  => pretty_number($planet['metal'], true, $planet['caps']['total_storage'][RES_METAL]),
93
      'METAL_PROD' => pretty_number($planet['caps']['total'][RES_METAL]),
94
95
      'CRYSTAL_CUR'  => pretty_number($planet['crystal'], true, $planet['caps']['total_storage'][RES_CRYSTAL]),
96
      'CRYSTAL_PROD' => pretty_number($planet['caps']['total'][RES_CRYSTAL]),
97
98
      'DEUTERIUM_CUR'  => pretty_number($planet['deuterium'], true, $planet['caps']['total_storage'][RES_DEUTERIUM]),
99
      'DEUTERIUM_PROD' => pretty_number($planet['caps']['total'][RES_DEUTERIUM]),
100
101
      'ENERGY_CUR' => pretty_number($planet['caps'][RES_ENERGY][BUILD_CREATE] - $planet['caps'][RES_ENERGY][BUILD_DESTROY], true, true),
102
      'ENERGY_MAX' => pretty_number($planet['caps'][RES_ENERGY][BUILD_CREATE]),
103
104
      'TEMP_MIN' => $planet['temp_min'],
105
      'TEMP_MAX' => $planet['temp_max'],
106
107
      'DENSITY_CLASS'      => $planet['density_index'],
108
      'DENSITY_RICHNESS'   => $planet_density[$planet['density_index']][UNIT_PLANET_DENSITY_RICHNESS],
109
      'DENSITY_CLASS_TEXT' => classLocale::$lang['uni_planet_density_types'][$planet['density_index']],
110
    )));
111
112
    $planet['fleet_list'] = $planet_template['fleet_list'];
113
    $planet['BUILDING_ID'] = $planet_template['BUILDING_ID'];
114
    $planet['hangar_que'] = $planet_template['hangar_que'];
115
    $planet['full_que'] = $list_planet_que;
116
117
    $total['fields'] += $planet['field_current'];
118
    $total['metal'] += $planet['metal'];
119
    $total['crystal'] += $planet['crystal'];
120
    $total['deuterium'] += $planet['deuterium'];
121
    $total['energy'] += $planet['energy_max'] - $planet['energy_used'];
122
123
    $total['fields_max'] += eco_planet_fields_max($planet);
124
    $total['metal_perhour'] += $planet['caps']['total'][RES_METAL];
125
    $total['crystal_perhour'] += $planet['caps']['total'][RES_CRYSTAL];
126
    $total['deuterium_perhour'] += $planet['caps']['total'][RES_DEUTERIUM];
127
    $total['energy_max'] += $planet['caps'][RES_ENERGY][BUILD_CREATE];
128
129
    $total['temp_min'] = min($planet['temp_min'], $total['temp_min']);
130
    $total['temp_max'] = max($planet['temp_max'], $total['temp_max']);
131
  }
132
133
  tpl_assign_fleet($template, $fleets);
134
135
  unset($planet);
136
137
  $show_groups = array(
138
    UNIT_STRUCTURES         => 'structures',
139
    UNIT_STRUCTURES_SPECIAL => 'structures',
140
    UNIT_SHIPS              => 'fleet',
141
    UNIT_DEFENCE            => 'defense',
142
  );
143
144
  foreach($show_groups as $unit_group_id => $mode) {
145
    $template->assign_block_vars('prods', array(
146
      'NAME' => classLocale::$lang['tech'][$unit_group_id],
147
    ));
148
    $unit_group = get_unit_param('techtree', $unit_group_id);
149
    foreach($unit_group as $unit_id) {
150
      $unit_count = $unit_count_abs = 0;
151
      $block_vars = array();
152
      $unit_is_factory = in_array($unit_id, $sn_group_factories) && get_unit_param($unit_id, P_MINING_IS_MANAGED);
153
      // $unit_db_name = pname_resource_name($unit_id);
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...
154
      foreach($planets as $planet) {
155
        $unit_level_plain = mrc_get_level($user, $planet, $unit_id, false, true);
156
157
        $level_plus['FACTORY'] = $unit_is_factory;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$level_plus was never initialized. Although not strictly required by PHP, it is generally a good practice to add $level_plus = 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...
158
        $level_plus['LEVEL_PLUS_YELLOW'] = 0;
0 ignored issues
show
Bug introduced by
The variable $level_plus does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
159
        $level_plus['LEVEL_PLUS_GREEN'] = 0;
160
161
        $level_plus['PERCENT'] = $unit_is_factory ? ($unit_level_plain ? $planet[pname_factory_production_field_name($unit_id)] * 10 : -1) : -1;
162
        switch($mode) {
163
          /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
164
          case 'structures':
165
            $level_plus_build = $ques[$planet['id']]['in_que'][que_get_unit_que($unit_id)][$user['id']][$planet['id']][$unit_id];
166
            if($level_plus_build)
167
            {
168
              $level_plus['LEVEL_PLUS_GREEN'] = $level_plus_build < 0 ? $level_plus_build : "+{$level_plus_build}";
169
              $total['units'][$unit_id]['LEVEL_PLUS_GREEN'] += $level_plus['LEVEL_PLUS_GREEN'];
170
            }
171
          break;
172
          */
173
174
          /** @noinspection PhpMissingBreakStatementInspection */
175
          case 'fleet':
176
            $level_plus['LEVEL_PLUS_YELLOW'] = $planet['fleet_list']['own']['total'][$unit_id] <= 0 ? $planet['fleet_list']['own']['total'][$unit_id] : "+{$planet['fleet_list']['own']['total'][$unit_id]}";
177
            $total['units'][$unit_id]['LEVEL_PLUS_YELLOW'] += $level_plus['LEVEL_PLUS_YELLOW'];
178
179
          case 'structures':
180
          case 'defense':
181
            $level_plus_build = $ques[$planet['id']]['in_que'][que_get_unit_que($unit_id)][$user['id']][$planet['id']][$unit_id];
182
            if($level_plus_build) {
183
              $level_plus['LEVEL_PLUS_GREEN'] = $level_plus_build < 0 ? $level_plus_build : "+{$level_plus_build}";
184
              // $level_plus['LEVEL_PLUS_GREEN'] = "+{$level_plus_build}";
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...
185
              $total['units'][$unit_id]['LEVEL_PLUS_GREEN'] += $level_plus['LEVEL_PLUS_GREEN'];
186
            }
187
          break;
188
189
          default:
190
          break;
191
        }
192
193
        $block_vars[] = array_merge($level_plus, array(
194
          'ID'    => $planet['id'],
195
          'TYPE'  => $planet['planet_type'],
196
          'LEVEL' => $unit_level_plain == 0 && !$level_plus['LEVEL_PLUS_YELLOW'] && !$level_plus['LEVEL_PLUS_GREEN'] ? '-' : $unit_level_plain,
197
        ));
198
        $unit_count += $unit_level_plain;
199
        $unit_count_abs += $unit_level_plain + abs($level_plus['LEVEL_PLUS_YELLOW']) + abs($level_plus['LEVEL_PLUS_GREEN']);
200
      }
201
202
      if($unit_count_abs) {
203
        $template->assign_block_vars('prods', array(
204
          'ID'    => $unit_id,
205
          'FIELD' => 'unit_' . $unit_id, // pname_resource_name($unit_id), // TODO Делать это прямо в темплейте
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...
206
          'NAME'  => classLocale::$lang['tech'][$unit_id],
207
          'MODE'  => $mode,
208
        ));
209
210
        foreach($block_vars as $block_var) {
211
          $template->assign_block_vars('prods.planet', $block_var);
212
        }
213
        $unit_green = $total['units'][$unit_id]['LEVEL_PLUS_GREEN'];
214
        $unit_yellow = $total['units'][$unit_id]['LEVEL_PLUS_YELLOW'];
215
        $template->assign_block_vars('prods.planet', array(
216
          'ID'                => 0,
217
          'LEVEL'             => $unit_count,
218
          'LEVEL_PLUS_GREEN'  => $unit_green == 0 ? '' : ($unit_green > 0 ? "+{$unit_green}" : $unit_green),
219
          'LEVEL_PLUS_YELLOW' => $unit_yellow == 0 ? '' : ($unit_yellow > 0 ? "+{$unit_yellow}" : $unit_yellow),
220
          'PERCENT'           => $unit_is_factory ? '' : -1,
221
          'FACTORY'           => $unit_is_factory,
222
        ));
223
      }
224
    }
225
  }
226
227
  $template->assign_block_vars('planet', array_merge(array(
228
    'ID'   => 0,
229
    'NAME' => classLocale::$lang['sys_total'],
230
231
    'FIELDS_CUR' => $total['fields'],
232
    'FIELDS_MAX' => $total['fields_max'],
233
234
    'METAL_CUR'  => pretty_number($total['metal']),
235
    'METAL_PROD' => pretty_number($total['metal_perhour']),
236
237
    'CRYSTAL_CUR'  => pretty_number($total['crystal']),
238
    'CRYSTAL_PROD' => pretty_number($total['crystal_perhour']),
239
240
    'DEUTERIUM_CUR'  => pretty_number($total['deuterium']),
241
    'DEUTERIUM_PROD' => pretty_number($total['deuterium_perhour']),
242
243
    'ENERGY_CUR' => pretty_number($total['energy']),
244
    'ENERGY_MAX' => pretty_number($total['energy_max']),
245
246
    'TEMP_MIN' => $total['temp_min'],
247
    'TEMP_MAX' => $total['temp_max'],
248
  )));
249
250
251
  $template->assign_vars(array(
252
    'COLONIES_CURRENT' => get_player_current_colonies($user),
253
    'COLONIES_MAX'     => get_player_max_colonies($user),
254
255
    'EXPEDITIONS_CURRENT' => FleetList::fleet_count_flying($user['id'], MT_EXPLORE),
256
    'EXPEDITIONS_MAX'     => get_player_max_expeditons($user),
257
258
    'PLANET_DENSITY_RICHNESS_NORMAL'  => PLANET_DENSITY_RICHNESS_NORMAL,
259
    'PLANET_DENSITY_RICHNESS_AVERAGE' => PLANET_DENSITY_RICHNESS_AVERAGE,
260
    'PLANET_DENSITY_RICHNESS_GOOD'    => PLANET_DENSITY_RICHNESS_GOOD,
261
    'PLANET_DENSITY_RICHNESS_PERFECT' => PLANET_DENSITY_RICHNESS_PERFECT,
262
  ));
263
264
  //$template->assign_recursive($template_result);
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% 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
  return $template;
267
}
268