Completed
Push — work-fleets ( 76d0ff...f3b03d )
by SuperNova.WS
05:19
created

includes/includes/flt_page5.inc::flt_build_gathering()   F

Complexity

Conditions 20
Paths 2888

Size

Total Lines 136
Code Lines 91

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 20
eloc 91
c 2
b 0
f 0
nc 2888
nop 1
dl 0
loc 136
rs 2

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
* flt_page5.inc
4
*
5
* @package fleet
6
* @version 1
7
*
8
* Revision History
9
* ================
10
*    1 - copyright (c) 2009-2011 by Gorlum for http://supernova.ws
11
*      [!] Write from scratch
12
*
13
**/
14
15
if(SN_IN_FLEET !== true) {
16
  classSupernova::$debug->error("Attempt to call FLEET page mode {$mode} directly - not from fleet.php", 'Forbidden', 403);
17
}
18
19
function flt_build_gathering($resources_taken = '') {
20
  global $planetrow, $user;
21
22
  // Caching sn_data names for quick access
23
  $lang_sys_planet_type = classLocale::$lang['sys_planet_type'];
24
  $lang_fl_attack_error = classLocale::$lang['fl_attack_error'];
25
26
  $planet_list = array();
27
28
  if(is_array($resources_taken))
29
  {
30
    $query = implode(',', array_keys($resources_taken));
31
    $query = " AND `destruyed` = 0 AND `id` IN ({$query})";
32
  } else {
33
    $query = '';
34
  }
35
36
  foreach(sn_get_groups('flt_transports') as $transport_id) {
37
    $transports[$transport_id] = get_unit_param($transport_id, P_CAPACITY);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$transports was never initialized. Although not strictly required by PHP, it is generally a good practice to add $transports = 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...
38
  }
39
  arsort($transports);
40
41
  $planets_db_list = db_planet_list_sorted($user, $planetrow['id'], '*', $query);
42
  !is_array($planets_db_list) ? $planets_db_list = array() : false;
43
  foreach($planets_db_list as $planet_db_data) {
44
  // begin planet loop
45
    if(!$query) {
46
      $resources_taken[$planet_db_data['id']] = 1;
47
    }
48
    sn_db_transaction_start();
49
    // Вот тут надо посчитать - отработать очереди и выяснить, сколько ресов на каждой планете
50
    $planet_db_data = sys_o_get_updated($user, $planet_db_data, SN_TIME_NOW, true);
51
    $planet_db_data = $planet_db_data['planet'];
52
    sn_db_transaction_commit();
53
54
    $planet_id = $planet_db_data['id'];
55
56
    $planet_resources = 0;
57
    foreach(sn_get_groups('resources_loot') as $resource_id) {
58
      if($resources_taken[$planet_id] == 1 || $resources_taken[$planet_id][$resource_id]) {
59
        $planet_resources += floor(mrc_get_level($user, $planet_db_data, $resource_id, true, true)); // $planet_db_data[get_unit_param($resource_id, P_NAME)]);
60
      }
61
    }
62
63
    $planet_list[$planet_id] = array(
64
      'ID'              => $planet_id,
65
      'NAME'            => $planet_db_data['name'],
66
      'GALAXY'          => $planet_db_data['galaxy'],
67
      'SYSTEM'          => $planet_db_data['system'],
68
      'PLANET'          => $planet_db_data['planet'],
69
      'TYPE'            => $planet_db_data['planet_type'],
70
      'TYPE_PRINT'      => $lang_sys_planet_type[$planet_db_data['planet_type']],
71
      'METAL'           => floor($planet_db_data['metal']),
72
      'CRYSTAL'         => floor($planet_db_data['crystal']),
73
      'DEUTERIUM'       => floor($planet_db_data['deuterium']),
74
      'METAL_TEXT'      => pretty_number($planet_db_data['metal']),
75
      'CRYSTAL_TEXT'    => pretty_number($planet_db_data['crystal']),
76
      'DEUTERIUM_TEXT'  => pretty_number($planet_db_data['deuterium']),
77
      'PLANET_DB_DATA'  => $planet_db_data,
78
      'RESOURCES'       => $planet_resources,
79
      'RESOURCES_TEXT'  => pretty_number($planet_resources),
80
    );
81
82
    $planet_data = &$planet_list[$planet_id];
83
//    $planet_data['RESOURCES'] = $planet_resources;
84
//    $planet_data['RESOURCES_TEXT'] = pretty_number($planet_resources);
85
86
    $fleet_capacity = 0;
87
    $ship_loadout = array();
88
    $fleet = array();
89
    foreach($transports as $ship_id => $ship_capacity) {
90
      if($ship_count = mrc_get_level($user, $planet_db_data, $ship_id, true, true)) {
91
        $ship_loadout[$ship_id]['capacity'] = $ship_count * $ship_capacity;
92
        $ship_loadout[$ship_id]['taken'] = 0;
93
        $fleet_capacity += $ship_loadout[$ship_id]['capacity'];
94
      }
95
    }
96
    $planet_data['FLEET_CAPACITY'] = $fleet_capacity;
97
    $planet_data['FLEET_CAPACITY_TEXT'] = pretty_number($fleet_capacity, true, -$planet_resources);
98
99
    $will_take = min($planet_resources, $fleet_capacity);
100
101
    foreach($ship_loadout as $ship_id => &$planet_ship) {
102
      $can_take = min($will_take, $planet_ship['capacity']);
103
      if($can_take <= 0) {
104
        continue;
105
      }
106
      $planet_ship['capacity'] -= $can_take;
107
      $planet_ship['taken'] += $can_take;
108
      $fleet[$ship_id] = ceil($planet_ship['taken'] / $transports[$ship_id]);
109
110
      $will_take -= $can_take;
111
      if($will_take <= 0) {
112
        break;
113
      }
114
    }
115
116
    if(!empty($fleet)) {
117
      $travel_data = flt_travel_data($user, $planetrow, $planet_db_data, $fleet, 10);
118
      $planet_data['FLEET_SPEED'] = $travel_data['fleet_speed'];
119
      $planet_data['DISTANCE']    = $travel_data['distance'];
120
      $planet_data['DURATION']    = $travel_data['duration'];
121
      $planet_data['CONSUMPTION'] = $travel_data['consumption'];
122
123
      if(floor(mrc_get_level($user, $planet_db_data, RES_DEUTERIUM, true)) >= $planet_data['CONSUMPTION']) {
124
        $will_take = min($planet_resources, $fleet_capacity) - $planet_data['CONSUMPTION'];
125
126
        foreach(sn_get_groups('resources_loot') as $resource_id) {
127
          if($resources_taken[$planet_id] != 1 && !$resources_taken[$planet_id][$resource_id]) {
128
            continue;
129
          }
130
131
          $resource_amount = floor(mrc_get_level($user, $planet_db_data, $resource_id, true, true));
132
133
          $fleet[$resource_id] = min($will_take, $resource_amount);
134
          $will_take -= $resource_amount;
135
136
          if($will_take <= 0) {
137
            break;
138
          }
139
        }
140
        $result = FLIGHT_ALLOWED;
141
      } else {
142
        $result = FLIGHT_RESOURCES_FUEL_NOT_ENOUGH;
143
      }
144
    } else {
145
      $result = FLIGHT_SHIPS_NO_SHIPS;
146
    }
147
148
    $planet_data['MESSAGE'] = $lang_fl_attack_error[$result];
149
    $planet_data['RESULT']  = $result;
150
    $planet_data['FLEET']   = $fleet;
151
  } // end planet loop
152
153
  return $planet_list;
154
}
155
156
$template = gettemplate('fleet5', true);
157
158
$resources_taken = sys_get_param('resources');
159
160
if(!empty($resources_taken))  { // begin processing parameters
161
  $planet_list = flt_build_gathering($resources_taken);
0 ignored issues
show
Bug introduced by
It seems like $resources_taken defined by sys_get_param('resources') on line 158 can also be of type array; however, flt_build_gathering() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
162
163
  foreach($planet_list as $planet_id => $planet_data) {
164
    if($planet_data['RESULT'] == FLIGHT_ALLOWED) {
165
      $planet_data['RESULT'] = flt_t_send_fleet($user, $planet_data['PLANET_DB_DATA'], $planetrow, $planet_data['FLEET'], MT_TRANSPORT);
166
    }
167
168
    $planet_data['MESSAGE'] = classLocale::$lang['fl_attack_error'][$planet_data['RESULT']];
169
170
    $template->assign_block_vars('results', $planet_data);
171
    if(!empty($planet_data['FLEET']) && $planet_data['RESULT'] == FLIGHT_ALLOWED) {
172
      foreach($planet_data['FLEET'] as $unit_id => $amount) {
173
        $template->assign_block_vars('results.units', array(
174
          'ID'     => $unit_id,
175
          'NAME'   => classLocale::$lang['tech'][$unit_id],
176
          'AMOUNT' => $amount
177
        ));
178
      }
179
    }
180
  }
181
} // end processing parameters
182
183
// Building list of own planets & moons
184
$planet_list = flt_build_gathering();
185
foreach($planet_list as $planet_data) {
186
  $planet_data['DURATION'] = $planet_data['DURATION'] ? pretty_time($planet_data['DURATION']) : classLocale::$lang['flt_no_fuel'];
187
  $template->assign_block_vars('colonies', $planet_data);
188
}
189
190
$template->assign_vars(array(
191
  'PAGE_HINT'      => classLocale::$lang['fl_page5_hint'],
192
  'METAL_NEED'     => pretty_number(max(0, -sys_get_param_float('metal'))),
193
  'CRYSTAL_NEED'   => pretty_number(max(0, -sys_get_param_float('crystal'))),
194
  'DEUTERIUM_NEED' => pretty_number(max(0, -sys_get_param_float('deuterium'))),
195
));
196
197
tpl_set_resource_info($template, $planetrow, array());
198
199
display($template, classLocale::$lang['fl_title']);
200