Test Setup Failed
Push — trunk ( cd2d21...adae1b )
by SuperNova.WS
09:23
created

imperium.php ➔ imperiumStoreMinesLoad()   C

Complexity

Conditions 12
Paths 9

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 17
nc 9
nop 1
dl 0
loc 27
rs 5.1612
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
// 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
function sn_imperium_view($template = null) {
15
  global $user, $lang;
16
17
  imperiumStoreMinesLoad($user);
18
19
  list($planets, $ques) = getUpdatedUserPlanetsAndQues($user);
20
21
  $template = gettemplate('imperium', $template);
22
23
  templateFillPercent($template);
24
25
  $template->assign_var('amount', count($planets) + 2);
26
27
  $imperiumStats = imperiumAssignFleetsAndCalculateTotal($template, $planets, $lang);
28
29
  $sn_group_factories = sn_get_groups('factories');
30
  foreach (
31
    [
32
      UNIT_STRUCTURES         => 'structures',
33
      UNIT_STRUCTURES_SPECIAL => 'structures',
34
      UNIT_SHIPS              => 'fleet',
35
      UNIT_DEFENCE            => 'defense',
36
    ] as $unit_group_id => $mode
37
  ) {
38
    $template->assign_block_vars('prods', array(
39
      'NAME' => $lang['tech'][$unit_group_id],
40
    ));
41
    $unit_group = get_unit_param('techtree', $unit_group_id);
42
    foreach ($unit_group as $unit_id) {
43
      $unit_count = $unit_count_abs = 0;
44
      $block_vars = array();
45
      $unit_is_factory = in_array($unit_id, $sn_group_factories) && get_unit_param($unit_id, P_MINING_IS_MANAGED);
46
      foreach ($planets as $planet) {
47
        $unit_level_plain = mrc_get_level($user, $planet, $unit_id, false, true);
48
49
        $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...
50
        $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...
51
        $level_plus['LEVEL_PLUS_GREEN'] = 0;
52
53
        $level_plus['PERCENT'] = $unit_is_factory ? ($unit_level_plain ? $planet[pname_factory_production_field_name($unit_id)] * 10 : -1) : -1;
54
        switch ($mode) {
55
56
          /** @noinspection PhpMissingBreakStatementInspection */
57
          case 'fleet':
58
            $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]}";
59
            $imperiumStats['units'][$unit_id]['LEVEL_PLUS_YELLOW'] += floatval($level_plus['LEVEL_PLUS_YELLOW']);
60
61
          case 'structures':
62
          case 'defense':
63
            $level_plus_build = $ques[$planet['id']]['in_que'][que_get_unit_que($unit_id)][$user['id']][$planet['id']][$unit_id];
64
            if ($level_plus_build) {
65
              $level_plus['LEVEL_PLUS_GREEN'] = $level_plus_build < 0 ? $level_plus_build : "+{$level_plus_build}";
66
              $imperiumStats['units'][$unit_id]['LEVEL_PLUS_GREEN'] += floatval($level_plus['LEVEL_PLUS_GREEN']);
67
            }
68
          break;
69
70
          default:
71
          break;
72
        }
73
74
        $block_vars[] = array_merge($level_plus, array(
75
          'ID'    => $planet['id'],
76
          'TYPE'  => $planet['planet_type'],
77
          'LEVEL' => $unit_level_plain == 0 && !$level_plus['LEVEL_PLUS_YELLOW'] && !$level_plus['LEVEL_PLUS_GREEN'] ? '-' : $unit_level_plain,
78
        ));
79
        $unit_count += $unit_level_plain;
80
        $unit_count_abs += $unit_level_plain + abs($level_plus['LEVEL_PLUS_YELLOW']) + abs($level_plus['LEVEL_PLUS_GREEN']);
81
      }
82
83
      if ($unit_count_abs) {
84
        $template->assign_block_vars('prods', array(
85
          'ID'    => $unit_id,
86
          'FIELD' => 'unit_' . $unit_id, // TODO Делать это прямо в темплейте
87
          'NAME'  => $lang['tech'][$unit_id],
88
          'MODE'  => $mode,
89
        ));
90
91
        foreach ($block_vars as $block_var) {
92
          $template->assign_block_vars('prods.planet', $block_var);
93
        }
94
        $unit_green = $imperiumStats['units'][$unit_id]['LEVEL_PLUS_GREEN'];
95
        $unit_yellow = $imperiumStats['units'][$unit_id]['LEVEL_PLUS_YELLOW'];
96
        $template->assign_block_vars('prods.planet', array(
97
          'ID'                => 0,
98
          'LEVEL'             => $unit_count,
99
          'LEVEL_PLUS_GREEN'  => $unit_green == 0 ? '' : ($unit_green > 0 ? "+{$unit_green}" : $unit_green),
100
          'LEVEL_PLUS_YELLOW' => $unit_yellow == 0 ? '' : ($unit_yellow > 0 ? "+{$unit_yellow}" : $unit_yellow),
101
          'PERCENT'           => $unit_is_factory ? '' : -1,
102
          'FACTORY'           => $unit_is_factory,
103
        ));
104
      }
105
    }
106
  }
107
108
  $template->assign_block_vars('planet', array_merge(array(
109
    'ID'   => 0,
110
    'NAME' => $lang['sys_total'],
111
112
    'FIELDS_CUR' => $imperiumStats['fields'],
113
    'FIELDS_MAX' => $imperiumStats['fields_max'],
114
115
    'METAL_CUR'  => pretty_number($imperiumStats['metal']),
116
    'METAL_PROD' => pretty_number($imperiumStats['metal_perhour']),
117
118
    'CRYSTAL_CUR'  => pretty_number($imperiumStats['crystal']),
119
    'CRYSTAL_PROD' => pretty_number($imperiumStats['crystal_perhour']),
120
121
    'DEUTERIUM_CUR'  => pretty_number($imperiumStats['deuterium']),
122
    'DEUTERIUM_PROD' => pretty_number($imperiumStats['deuterium_perhour']),
123
124
    'ENERGY_CUR' => pretty_number($imperiumStats['energy']),
125
    'ENERGY_MAX' => pretty_number($imperiumStats['energy_max']),
126
127
    'TEMP_MIN' => $imperiumStats['temp_min'],
128
    'TEMP_MAX' => $imperiumStats['temp_max'],
129
  )));
130
131
132
  $template->assign_vars(array(
133
    'COLONIES_CURRENT' => get_player_current_colonies($user),
134
    'COLONIES_MAX'     => get_player_max_colonies($user),
135
136
    'EXPEDITIONS_CURRENT' => fleet_count_flying($user['id'], MT_EXPLORE),
137
    'EXPEDITIONS_MAX'     => get_player_max_expeditons($user),
138
139
    'PLANET_DENSITY_RICHNESS_NORMAL'  => PLANET_DENSITY_RICHNESS_NORMAL,
140
    'PLANET_DENSITY_RICHNESS_AVERAGE' => PLANET_DENSITY_RICHNESS_AVERAGE,
141
    'PLANET_DENSITY_RICHNESS_GOOD'    => PLANET_DENSITY_RICHNESS_GOOD,
142
    'PLANET_DENSITY_RICHNESS_PERFECT' => PLANET_DENSITY_RICHNESS_PERFECT,
143
  ));
144
145
  return $template;
146
}
147
148
/**
149
 * Store current mines load in DB
150
 *
151
 * @param array $user
152
 */
153
function imperiumStoreMinesLoad($user) {
154
  if (!sys_get_param('save_production') || !is_array($production = sys_get_param('percent')) || empty($production)) {
155
    return;
156
  }
157
158
  $sn_group_factories = sn_get_groups('factories');
159
160
  $query = [];
161
  foreach (DBStaticPlanet::db_planet_list_sorted($user, false, '*') as $planet) {
162
    foreach ($sn_group_factories as $factory_unit_id) {
163
      $unit_db_name_porcent = pname_factory_production_field_name($factory_unit_id);
164
      if (
165
        get_unit_param($factory_unit_id, P_MINING_IS_MANAGED)
166
        && isset($production[$factory_unit_id][$planet['id']])
167
        && ($actual_porcent = intval($production[$factory_unit_id][$planet['id']] / 10)) >= 0
168
        && $actual_porcent <= 10
169
        && $actual_porcent != $planet[$unit_db_name_porcent]
170
      ) {
171
        $query[$planet['id']][] = "{$unit_db_name_porcent} = {$actual_porcent}";
172
      }
173
    }
174
  }
175
176
  foreach ($query as $planet_id => $query_data) {
177
    DBStaticPlanet::db_planet_set_by_id($planet_id, implode(',', $query_data));
178
  }
179
}
180
181
/**
182
 * @param template    $template
183
 * @param array[]     $planets
184
 * @param classLocale $lang
185
 *
186
 * @return array
187
 */
188
function imperiumAssignFleetsAndCalculateTotal($template, $planets, $lang) {
189
  $planet_density = sn_get_groups('planet_density');
190
191
  $imperiumStats = array();
192
  $imperiumStats['temp_min'] = 1000;
193
  $imperiumStats['temp_max'] = -999;
194
195
  $fleets = [];
196
  foreach ($planets as $planetId => &$planet) {
197
    $templatizedPlanet = tpl_parse_planet($planet, $fleets);
198
199
    $template->assign_block_vars('planet', array_merge($templatizedPlanet, array(
200
      'METAL_CUR'  => pretty_number($planet['metal'], true, $planet['caps']['total_storage'][RES_METAL]),
201
      'METAL_PROD' => pretty_number($planet['caps']['total'][RES_METAL]),
202
203
      'CRYSTAL_CUR'  => pretty_number($planet['crystal'], true, $planet['caps']['total_storage'][RES_CRYSTAL]),
204
      'CRYSTAL_PROD' => pretty_number($planet['caps']['total'][RES_CRYSTAL]),
205
206
      'DEUTERIUM_CUR'  => pretty_number($planet['deuterium'], true, $planet['caps']['total_storage'][RES_DEUTERIUM]),
207
      'DEUTERIUM_PROD' => pretty_number($planet['caps']['total'][RES_DEUTERIUM]),
208
209
      'ENERGY_CUR' => pretty_number($planet['caps'][RES_ENERGY][BUILD_CREATE] - $planet['caps'][RES_ENERGY][BUILD_DESTROY], true, true),
210
      'ENERGY_MAX' => pretty_number($planet['caps'][RES_ENERGY][BUILD_CREATE]),
211
212
      'TEMP_MIN' => $planet['temp_min'],
213
      'TEMP_MAX' => $planet['temp_max'],
214
215
      'DENSITY_CLASS'      => $planet['density_index'],
216
      'DENSITY_RICHNESS'   => $planet_density[$planet['density_index']][UNIT_PLANET_DENSITY_RICHNESS],
217
      'DENSITY_CLASS_TEXT' => $lang['uni_planet_density_types'][$planet['density_index']],
218
    )));
219
220
//    $planet['fleet_list'] = $planet_template['fleet_list'];
221
//    $planet['BUILDING_ID'] = $planet_template['BUILDING_ID'];
222
//    $planet['hangar_que'] = $planet_template['hangar_que'];
223
//    $planet['full_que'] = $list_planet_que;
224
225
    $imperiumStats['fields'] += $planet['field_current'];
226
    $imperiumStats['metal'] += $planet['metal'];
227
    $imperiumStats['crystal'] += $planet['crystal'];
228
    $imperiumStats['deuterium'] += $planet['deuterium'];
229
    $imperiumStats['energy'] += $planet['energy_max'] - $planet['energy_used'];
230
231
    $imperiumStats['fields_max'] += eco_planet_fields_max($planet);
232
    $imperiumStats['metal_perhour'] += $planet['caps']['total'][RES_METAL];
233
    $imperiumStats['crystal_perhour'] += $planet['caps']['total'][RES_CRYSTAL];
234
    $imperiumStats['deuterium_perhour'] += $planet['caps']['total'][RES_DEUTERIUM];
235
    $imperiumStats['energy_max'] += $planet['caps'][RES_ENERGY][BUILD_CREATE];
236
237
    $imperiumStats['temp_min'] = min($planet['temp_min'], $imperiumStats['temp_min']);
238
    $imperiumStats['temp_max'] = max($planet['temp_max'], $imperiumStats['temp_max']);
239
  }
240
241
  tpl_assign_fleet($template, $fleets);
242
243
  return $imperiumStats;
244
}
245
246
/**
247
 * @param template $template
248
 */
249
function templateFillPercent($template) {
250
  for ($i = 100; $i >= 0; $i -= 10) {
251
    $template->assign_block_vars('percent', array('PERCENT' => $i));
252
  }
253
}
254
255
/**
256
 * @param array $user
257
 *
258
 * @return array[]
259
 */
260
function getUpdatedUserPlanetsAndQues($user) {
261
  $planets = array();
262
  $ques = array();
263
  $planet_row_list = DBStaticPlanet::db_planet_list_sorted($user);
264
  foreach ($planet_row_list as $planet) {
265
    sn_db_transaction_start();
266
    $global_data = sys_o_get_updated($user, $planet['id'], SN_TIME_NOW, false, true);
267
    $planets[$planet['id']] = $global_data['planet'];
268
    $ques[$planet['id']] = $global_data['que'];
269
    sn_db_transaction_commit();
270
  }
271
272
  return array($planets, $ques);
273
}
274