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

tpl_helpers.php ➔ sn_tplParseFleetObject()   F

Complexity

Conditions 20
Paths > 20000

Size

Total Lines 101
Code Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 1 Features 0
Metric Value
cc 20
eloc 72
nc 32768
nop 4
dl 0
loc 101
rs 2
c 8
b 1
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
// Compare function to sort fleet in time order
4
function tpl_assign_fleet_compare($a, $b) {
5
  if($a['fleet']['OV_THIS_PLANET'] == $b['fleet']['OV_THIS_PLANET']) {
6
    if($a['fleet']['OV_LEFT'] == $b['fleet']['OV_LEFT']) {
7
      return 0;
8
    }
9
10
    return ($a['fleet']['OV_LEFT'] < $b['fleet']['OV_LEFT']) ? -1 : 1;
11
  } else {
12
    return $a['fleet']['OV_THIS_PLANET'] ? -1 : 1;
13
  }
14
}
15
16
/**
17
 * @param template $template
18
 * @param array    $fleets
19
 * @param string   $js_name
20
 */
21
function tpl_assign_fleet(&$template, $fleets, $js_name = 'fleets') {
22
  if(!$fleets) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fleets of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
23
    return;
24
  }
25
26
  usort($fleets, 'tpl_assign_fleet_compare');
27
28
  foreach($fleets as $fleet_data) {
29
    $template->assign_block_vars($js_name, $fleet_data['fleet']);
30
31
    if($fleet_data['ships']) {
32
      foreach($fleet_data['ships'] as $ship_data) {
33
        $template->assign_block_vars("{$js_name}.ships", $ship_data);
34
      }
35
    }
36
  }
37
}
38
39
// function that parses internal fleet representation (as array(id => count))
40
function tpl_parse_fleet_sn($fleet, $fleet_id) {
41
  global $user;
42
43
  $user_data = &$user;
44
45
  $return['fleet'] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = 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...
46
    'ID' => $fleet_id,
47
48
    'METAL'     => $fleet[RES_METAL],
49
    'CRYSTAL'   => $fleet[RES_CRYSTAL],
50
    'DEUTERIUM' => $fleet[RES_DEUTERIUM],
51
  );
52
53
  foreach($fleet as $ship_id => $ship_amount) {
54
    if(in_array($ship_id, sn_get_groups('fleet'))) {
55
      $single_ship_data = get_ship_data($ship_id, $user_data);
56
      $return['ships'][$ship_id] = array(
57
        'ID'          => $ship_id,
58
        'NAME'        => classLocale::$lang['tech'][$ship_id],
59
        'AMOUNT'      => $ship_amount,
60
        'CONSUMPTION' => $single_ship_data['consumption'],
61
        'SPEED'       => $single_ship_data['speed'],
62
        'CAPACITY'    => $single_ship_data['capacity'],
63
      );
64
    }
65
  }
66
67
  return $return;
68
}
69
70
// Used in UNIT_CAPTAIN
71
/**
72
 * @param Fleet $objFleet
73
 * @param       $index
74
 * @param bool  $user_data
75
 *
76
 * @return array
77
 */
78
function tplParseFleetObject(Fleet $objFleet, $index, $user_data = false) { return sn_function_call(__FUNCTION__, array($objFleet, $index, $user_data, &$result)); }
0 ignored issues
show
Bug introduced by
The variable $result 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...
79
80
/**
81
 * @param Fleet $objFleet
82
 * @param       $index
83
 * @param bool  $user_data
84
 * @param       $result
85
 *
86
 * @return array
87
 */
88
function sn_tplParseFleetObject(Fleet $objFleet, $index, $user_data = false, &$result) {
89
  global $user;
90
91
  $result = array();
92
93
  if(!$user_data) {
94
    $user_data = $user;
95
  }
96
97
  if(!$objFleet->isReturning() && $objFleet->mission_type == MT_ACS) {
98
    $aks = db_acs_get_by_group_id($objFleet->group_id);
99
  }
100
101
  $spy_level = $user['id'] == $objFleet->playerOwnerId ? 100 : GetSpyLevel($user);
102
103
  $fleet_resources = $objFleet->resourcesGetList();
104
  $result['fleet'] = isset($result['fleet']) ? $result['fleet'] : array();
105
  $result['fleet'] = array(
106
    'NUMBER' => $index,
107
108
    'ID'           => $objFleet->dbId,
109
    'OWNER'        => $objFleet->playerOwnerId,
110
    'TARGET_OWNER' => $objFleet->target_owner_id,
111
112
    'MESSAGE'      => $objFleet->isReturning(),
113
    'MISSION'      => $objFleet->mission_type,
114
    'MISSION_NAME' => classLocale::$lang['type_mission'][$objFleet->mission_type],
115
    'ACS'          => !empty($aks['name']) ? $aks['name'] : (!empty($objFleet->group_id) ? $objFleet->group_id : ''),
116
    'AMOUNT'       => $spy_level >= 4 ? (pretty_number($objFleet->shipsGetTotal()) . (array_sum($fleet_resources) ? '+' : '')) : '?',
117
118
    'METAL'     => $spy_level >= 8 ? $fleet_resources[RES_METAL] : 0,
119
    'CRYSTAL'   => $spy_level >= 8 ? $fleet_resources[RES_CRYSTAL] : 0,
120
    'DEUTERIUM' => $spy_level >= 8 ? $fleet_resources[RES_DEUTERIUM] : 0,
121
122
    'START_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$objFleet->fleet_start_type],
123
    'START_COORDS'       => "[{$objFleet->fleet_start_galaxy}:{$objFleet->fleet_start_system}:{$objFleet->fleet_start_planet}]",
124
    'START_TIME_TEXT'    => date(FMT_DATE_TIME, $objFleet->time_return_to_source + SN_CLIENT_TIME_DIFF),
125
    'START_LEFT'         => floor($objFleet->time_return_to_source + 1 - SN_TIME_NOW),
126
    'START_URL'          => uni_render_coordinates_href($objFleet->launch_coordinates_typed(), '', 3),
127
128
    'END_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$objFleet->fleet_end_type],
129
    'END_COORDS'       => "[{$objFleet->fleet_end_galaxy}:{$objFleet->fleet_end_system}:{$objFleet->fleet_end_planet}]",
130
    'END_TIME_TEXT'    => date(FMT_DATE_TIME, $objFleet->time_arrive_to_target + SN_CLIENT_TIME_DIFF),
131
    'END_LEFT'         => floor($objFleet->time_arrive_to_target + 1 - SN_TIME_NOW),
132
    'END_URL'          => uni_render_coordinates_href($objFleet->target_coordinates_typed(), '', 3),
133
134
    'STAY_TIME' => date(FMT_DATE_TIME, $objFleet->time_mission_job_complete + SN_CLIENT_TIME_DIFF),
135
    'STAY_LEFT' => floor($objFleet->time_mission_job_complete + 1 - SN_TIME_NOW),
136
  );
137
138
  if(property_exists($objFleet, 'fleet_start_name')) {
139
    $result['START_NAME'] = $objFleet->fleet_start_name;
140
  }
141
  if(property_exists($objFleet, 'fleet_end_name')) {
142
    $result['END_NAME'] = $objFleet->fleet_end_name;
143
  }
144
145
  if(property_exists($objFleet, 'event_time')) {
146
    $result['fleet'] = array_merge($result['fleet'], array(
147
      'OV_LABEL'        => $objFleet->ov_label,
148
      'EVENT_TIME_TEXT' => property_exists($objFleet, 'event_time') ? date(FMT_DATE_TIME, $objFleet->event_time + SN_CLIENT_TIME_DIFF) : '',
149
      'OV_LEFT'         => floor($objFleet->event_time + 1 - SN_TIME_NOW),
150
      'OV_THIS_PLANET'  => $objFleet->ov_this_planet,
151
    ));
152
  }
153
154
  $ship_list_fully_parsed = $objFleet->shipsGetArray();
155
156
  $ship_id = 0;
157
  $result['ships'] = array();
158
  if($spy_level >= 6) {
159
    foreach($ship_list_fully_parsed as $ship_sn_id => $ship_amount) {
160
      if($spy_level >= 10) {
161
        $single_ship_data = get_ship_data($ship_sn_id, $user_data);
162
        $result['ships'][$ship_sn_id] = array(
163
          'ID'          => $ship_sn_id,
164
          'NAME'        => classLocale::$lang['tech'][$ship_sn_id],
165
          'AMOUNT'      => $ship_amount,
166
          'AMOUNT_TEXT' => pretty_number($ship_amount),
167
          'CONSUMPTION' => $single_ship_data['consumption'],
168
          'SPEED'       => $single_ship_data['speed'],
169
          'CAPACITY'    => $single_ship_data['capacity'],
170
        );
171
      } else {
172
        $result['ships'][$ship_sn_id] = array(
173
          'ID'               => $ship_id++,
174
          'NAME'             => classLocale::$lang['tech'][UNIT_SHIPS],
175
          'AMOUNT'           => $ship_amount,
176
          'AMOUNT_TEXT'      => pretty_number($ship_amount),
177
          'CONSUMPTION'      => 0,
178
          'CONSUMPTION_TEXT' => '0',
179
          'SPEED'            => 0,
180
          'CAPACITY'         => 0,
181
        );
182
      }
183
    }
184
  } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
185
  }
186
187
  return $result;
188
}
189
190
function tpl_parse_planet_que($que, $planet, $que_id) {
191
  $hangar_que = array();
192
  $que_hangar = $que['ques'][$que_id][$planet['id_owner']][$planet['id']];
193
  if(!empty($que_hangar)) {
194
    foreach($que_hangar as $que_item) {
195
      $hangar_que['que'][] = array('id' => $que_item['que_unit_id'], 'count' => $que_item['que_unit_amount']);
196
      $hangar_que[$que_item['que_unit_id']] += $que_item['que_unit_amount'];
197
    }
198
  }
199
200
  return $hangar_que;
201
}
202
203
function tpl_parse_planet($planet) {
204
  $fleet_list = FleetList::EMULATE_flt_get_fleets_to_planet($planet);
205
206
  $que = que_get($planet['id_owner'], $planet['id'], false);
207
208
  $structure_que = tpl_parse_planet_que($que, $planet, QUE_STRUCTURES); // TODO Заменить на que_tpl_parse_element($que_element);
209
  $structure_que_first = is_array($structure_que['que']) ? reset($structure_que['que']) : array();
210
  $hangar_que = tpl_parse_planet_que($que, $planet, SUBQUE_FLEET); // TODO Заменить на que_tpl_parse_element($que_element);
211
  $hangar_que_first = is_array($hangar_que['que']) ? reset($hangar_que['que']) : array();
212
  $defense_que = tpl_parse_planet_que($que, $planet, SUBQUE_DEFENSE); // TODO Заменить на que_tpl_parse_element($que_element);
213
  $defense_que_first = is_array($defense_que['que']) ? reset($defense_que['que']) : array();
214
215
  $result = array(
216
    'ID'    => $planet['id'],
217
    'NAME'  => $planet['name'],
218
    'IMAGE' => $planet['image'],
219
220
    'GALAXY'      => $planet['galaxy'],
221
    'SYSTEM'      => $planet['system'],
222
    'PLANET'      => $planet['planet'],
223
    'TYPE'        => $planet['planet_type'],
224
    'COORDINATES' => uni_render_coordinates($planet),
225
226
    'METAL_PERCENT'     => $planet['metal_mine_porcent'] * 10,
227
    'CRYSTAL_PERCENT'   => $planet['crystal_mine_porcent'] * 10,
228
    'DEUTERIUM_PERCENT' => $planet['deuterium_sintetizer_porcent'] * 10,
229
230
    'STRUCTURE' => isset($structure_que_first['id']) ? classLocale::$lang['tech'][$structure_que_first['id']] : '',
231
232
    'HANGAR'     => isset($hangar_que_first['id']) ? classLocale::$lang['tech'][$hangar_que_first['id']] : '',
233
    'hangar_que' => $hangar_que,
234
235
    'DEFENSE'     => isset($defense_que_first['id']) ? classLocale::$lang['tech'][$defense_que_first['id']] : '',
236
    'defense_que' => $defense_que,
237
238
    'FIELDS_CUR' => $planet['field_current'],
239
    'FIELDS_MAX' => eco_planet_fields_max($planet),
240
    'FILL'       => min(100, floor($planet['field_current'] / eco_planet_fields_max($planet) * 100)),
241
242
    'FLEET_OWN'     => $fleet_list['own']['count'],
243
    'FLEET_ENEMY'   => $fleet_list['enemy']['count'],
244
    'FLEET_NEUTRAL' => $fleet_list['neutral']['count'],
245
246
    'fleet_list' => $fleet_list,
247
248
    'PLANET_GOVERNOR_ID'        => $planet['PLANET_GOVERNOR_ID'],
249
    'PLANET_GOVERNOR_NAME'      => classLocale::$lang['tech'][$planet['PLANET_GOVERNOR_ID']],
250
    'PLANET_GOVERNOR_LEVEL'     => $planet['PLANET_GOVERNOR_LEVEL'],
251
    'PLANET_GOVERNOR_LEVEL_MAX' => get_unit_param($planet['PLANET_GOVERNOR_ID'], P_MAX_STACK),
252
  );
253
254
  if(!empty($que['ques'][QUE_STRUCTURES][$planet['id_owner']][$planet['id']])) {
255
    $result['building_que'] = array();
256
    $building_que = &$que['ques'][QUE_STRUCTURES][$planet['id_owner']][$planet['id']];
257
    foreach($building_que as $que_element) {
258
      $result['building_que'][] = que_tpl_parse_element($que_element);
259
    }
260
  }
261
262
  return $result;
263
}
264
265
/**
266
 * @param Fleet[] $array_of_Fleet
267
 *
268
 * @return array
269
 */
270
function flt_get_fleets_to_planet_by_array_of_Fleet($array_of_Fleet) {
271
  global $user;
272
273
  if(empty($array_of_Fleet)) {
274
    return false;
275
  }
276
277
  $fleet_list = array();
278
  foreach($array_of_Fleet as $fleet) {
279
    if($fleet->playerOwnerId == $user['id']) {
280
      if($fleet->mission_type == MT_MISSILE) {
281
        continue;
282
      }
283
      $fleet_ownage = 'own';
284
    } else {
285
      switch($fleet->mission_type) {
286
        case MT_ATTACK:
287
        case MT_ACS:
288
        case MT_DESTROY:
289
        case MT_MISSILE:
290
          $fleet_ownage = 'enemy';
291
        break;
292
293
        default:
294
          $fleet_ownage = 'neutral';
295
        break;
296
297
      }
298
    }
299
300
    $fleet_list[$fleet_ownage]['fleets'][$fleet->dbId] = $fleet;
301
302
    if($fleet->isReturning() || (!$fleet->isReturning() && $fleet->mission_type == MT_RELOCATE) || ($fleet->target_owner_id != $user['id'])) {
303
      $fleet_sn = $fleet->shipsGetArray();
304
      foreach($fleet_sn as $ship_id => $ship_amount) {
305
        if(in_array($ship_id, sn_get_groups('fleet'))) {
306
          $fleet_list[$fleet_ownage]['total'][$ship_id] += $ship_amount;
307
        }
308
      }
309
    }
310
311
    $fleet_list[$fleet_ownage]['count']++;
312
    $fleet_list[$fleet_ownage]['amount'] += $fleet->shipsGetTotal();
313
    $fleet_resources = $fleet->resourcesGetList();
314
    $fleet_list[$fleet_ownage]['total'][RES_METAL] += $fleet_resources[RES_METAL];
315
    $fleet_list[$fleet_ownage]['total'][RES_CRYSTAL] += $fleet_resources[RES_CRYSTAL];
316
    $fleet_list[$fleet_ownage]['total'][RES_DEUTERIUM] += $fleet_resources[RES_DEUTERIUM];
317
  }
318
319
  return $fleet_list;
320
}
321
322
function tpl_set_resource_info(template &$template, $planet_row, $fleets_to_planet = array(), $round = 0) {
323
  $template->assign_vars(array(
324
    'RESOURCE_ROUNDING' => $round,
325
326
    'ENERGY_BALANCE' => pretty_number($planet_row['energy_max'] - $planet_row['energy_used'], true, true),
327
    'ENERGY_MAX'     => pretty_number($planet_row['energy_max'], true, -$planet_row['energy_used']),
328
    'ENERGY_FILL'    => round(($planet_row["energy_used"] / ($planet_row["energy_max"] + 1)) * 100, 0),
329
330
    'PLANET_METAL'            => round($planet_row["metal"], $round),
331
    'PLANET_METAL_TEXT'       => pretty_number($planet_row["metal"], $round, $planet_row["metal_max"]),
332
    'PLANET_METAL_MAX'        => round($planet_row["metal_max"], $round),
333
    'PLANET_METAL_MAX_TEXT'   => pretty_number($planet_row["metal_max"], $round, -$planet_row["metal"]),
334
    'PLANET_METAL_FILL'       => round(($planet_row["metal"] / ($planet_row["metal_max"] + 1)) * 100, 0),
335
    'PLANET_METAL_PERHOUR'    => round($planet_row["metal_perhour"], 5),
336
    'PLANET_METAL_FLEET_TEXT' => pretty_number($fleets_to_planet[$planet_row['id']]['fleet']['METAL'], $round, true),
337
338
    'PLANET_CRYSTAL'            => round($planet_row["crystal"], $round),
339
    'PLANET_CRYSTAL_TEXT'       => pretty_number($planet_row["crystal"], $round, $planet_row["crystal_max"]),
340
    'PLANET_CRYSTAL_MAX'        => round($planet_row["crystal_max"], $round),
341
    'PLANET_CRYSTAL_MAX_TEXT'   => pretty_number($planet_row["crystal_max"], $round, -$planet_row["crystal"]),
342
    'PLANET_CRYSTAL_FILL'       => round(($planet_row["crystal"] / ($planet_row["crystal_max"] + 1)) * 100, 0),
343
    'PLANET_CRYSTAL_PERHOUR'    => round($planet_row["crystal_perhour"], 5),
344
    'PLANET_CRYSTAL_FLEET_TEXT' => pretty_number($fleets_to_planet[$planet_row['id']]['fleet']['CRYSTAL'], $round, true),
345
346
    'PLANET_DEUTERIUM'            => round($planet_row["deuterium"], $round),
347
    'PLANET_DEUTERIUM_TEXT'       => pretty_number($planet_row["deuterium"], $round, $planet_row["deuterium_max"]),
348
    'PLANET_DEUTERIUM_MAX'        => round($planet_row["deuterium_max"], $round),
349
    'PLANET_DEUTERIUM_MAX_TEXT'   => pretty_number($planet_row["deuterium_max"], $round, -$planet_row["deuterium"]),
350
    'PLANET_DEUTERIUM_FILL'       => round(($planet_row["deuterium"] / ($planet_row["deuterium_max"] + 1)) * 100, 0),
351
    'PLANET_DEUTERIUM_PERHOUR'    => round($planet_row["deuterium_perhour"], 5),
352
    'PLANET_DEUTERIUM_FLEET_TEXT' => pretty_number($fleets_to_planet[$planet_row['id']]['fleet']['DEUTERIUM'], $round, true),
353
  ));
354
}
355