Completed
Push — trunk ( cc9b3e...f009e4 )
by SuperNova.WS
04:37
created

PageImperium   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 396
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 396
ccs 0
cts 243
cp 0
rs 8.6206
c 0
b 0
f 0
wmc 50

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A modelStatic() 0 7 1
A viewStatic() 0 7 1
B tplRenderPlanets() 0 49 4
C modelAdjustMinePercent() 0 31 12
A tplRenderFleets() 0 9 3
A getUpdatedUserPlanetsAndQues() 0 13 2
B tplTotalPlanetInfo() 0 44 2
B view() 0 27 2
A fleetGetFlyingToPlanets() 0 7 2
B tplRenderUnitLine() 0 29 5
A tplAddGlobals() 0 14 1
F imperiumTemplatizeUnitGroup() 0 48 14

How to fix   Complexity   

Complex Class

Complex classes like PageImperium 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 PageImperium, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Created by Gorlum 01.10.2017 17:53
4
 */
5
6
namespace Deprecated;
7
8
use \template;
9
use \classLocale;
10
use \DBStaticPlanet;
11
use \HelperString;
12
13
class PageImperium {
14
15
  const GROUPS_TO_NAMES = [
16
    UNIT_STRUCTURES         => 'structures',
17
    UNIT_STRUCTURES_SPECIAL => 'structures',
18
    UNIT_SHIPS              => 'fleet',
19
    UNIT_DEFENCE            => 'defense',
20
  ];
21
22
  /**
23
   * @var classLocale $lang ;
24
   */
25
  protected $lang;
26
27
28
  /**
29
   * @param template|null $template
30
   */
31
  public static function viewStatic(template $template = null) {
32
    $that = new static();
33
34
    $template = $that->view($template);
35
    unset($that);
36
37
    return $template;
38
  }
39
40
  /**
41
   * @param template|null $template
42
   */
43
  public static function modelStatic(template $template = null) {
44
    $that = new static();
45
46
    $that->modelAdjustMinePercent();
47
    unset($that);
48
49
    return $template;
50
  }
51
52
  public function __construct() {
53
    global $lang;
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...
54
    $this->lang = $lang;
55
  }
56
57
  /**
58
   * @param template|null $template
59
   *
60
   * @return template
61
   */
62
  public function view(template $template = null) {
63
    global $user;
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...
64
65
//    $this->modelAdjustMinePercent();
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...
66
67
    list($planets, $ques) = $this->getUpdatedUserPlanetsAndQues($user);
68
    $fleets = $this->fleetGetFlyingToPlanets($planets);
69
70
    $template = gettemplate('imperium', $template);
71
72
    $template->assign_recursive(templateFillPercent());
73
74
    $template->assign_recursive($this->tplRenderPlanets($planets, $fleets));
75
    $template->assign_recursive($this->tplRenderFleets($fleets));
76
    $this->tplTotalPlanetInfo($template, $planets);
77
78
    foreach (self::GROUPS_TO_NAMES as $unit_group_id => $internalGroupName) {
79
      $template->assign_block_vars('prods', array(
80
        'NAME' => $this->lang['tech'][$unit_group_id],
81
      ));
82
      $this->imperiumTemplatizeUnitGroup($user, $template, $unit_group_id, $planets, $ques, $fleets);
83
    }
84
85
    $template->assign_var('amount', count($planets) + 2);
86
    $this->tplAddGlobals($user, $template);
87
88
    return $template;
89
  }
90
91
  /**
92
   * Store current mines load in DB
93
   */
94
  protected function modelAdjustMinePercent() {
95
    global $user;
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...
96
97
    if (!sys_get_param('save_production') || !is_array($production = sys_get_param('percent')) || empty($production)) {
98
      return;
99
    }
100
101
    $sn_group_factories = sn_get_groups('factories');
102
103
    foreach (DBStaticPlanet::db_planet_list_sorted($user, false, '*') as $planetId => $planet) {
104
      $query = [];
105
      foreach ($sn_group_factories as $factory_unit_id) {
106
        $unit_db_name_porcent = pname_factory_production_field_name($factory_unit_id);
107
        if (
108
          // Changes required to mine production
109
          isset($production[$factory_unit_id][$planet['id']])
110
          // If mine is managed
111
          && get_unit_param($factory_unit_id, P_MINING_IS_MANAGED)
112
          // Input value is valid
113
          && ($actual_porcent = intval($production[$factory_unit_id][$planet['id']] / 10)) >= 0
114
          && $actual_porcent <= 10
115
          // And changes really should be stored to DB
116
          && $actual_porcent != $planet[$unit_db_name_porcent]
117
        ) {
118
          $actual_porcent = intval($actual_porcent);
119
          $query[] = "`{$unit_db_name_porcent}` = {$actual_porcent}";
120
        }
121
      }
122
123
      if (!empty($query)) {
124
        DBStaticPlanet::db_planet_set_by_id($planet['id'], implode(',', $query));
125
      }
126
    }
127
  }
128
129
  /**
130
   * @param array $user
131
   *
132
   * @return array[]
133
   */
134
  protected function getUpdatedUserPlanetsAndQues($user) {
135
    $planets = array();
136
    $ques = array();
137
    $planet_row_list = DBStaticPlanet::db_planet_list_sorted($user);
138
    foreach ($planet_row_list as $planet) {
139
      sn_db_transaction_start();
140
      $global_data = sys_o_get_updated($user, $planet['id'], SN_TIME_NOW, false, true);
141
      $planets[$planet['id']] = $global_data['planet'];
142
      $ques[$planet['id']] = $global_data['que'];
143
      sn_db_transaction_commit();
144
    }
145
146
    return array($planets, $ques);
147
  }
148
149
  /**
150
   * @param array    $user
151
   * @param template $template
152
   * @param int      $unit_group_id
153
   * @param array[]  $planets
154
   * @param array[]  $ques
155
   * @param array    $fleets
156
   */
157
  protected function imperiumTemplatizeUnitGroup(&$user, $template, $unit_group_id, $planets, $ques, $fleets) {
158
    $sn_group_factories = sn_get_groups('factories');
159
160
    foreach (get_unit_param('techtree', $unit_group_id) as $unit_id) {
161
      $unit_count = $unit_count_abs = 0;
162
      $block_vars = array();
163
      $unit_is_factory = in_array($unit_id, $sn_group_factories) && get_unit_param($unit_id, P_MINING_IS_MANAGED);
164
      foreach ($planets as $planet) {
165
        $unit_level_plain = mrc_get_level($user, $planet, $unit_id, false, true);
166
167
        $levelGreen = 0;
168
        $levelYellow = 0;
169
170
        switch ($unit_group_id) {
171
          /** @noinspection PhpMissingBreakStatementInspection */
172
          case UNIT_SHIPS:
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
173
            $levelYellow = !empty($fleets[$planet['id']]['own']['total'][$unit_id]) ? floatval($fleets[$planet['id']]['own']['total'][$unit_id]) : 0;
174
175
          case UNIT_STRUCTURES:
176
          case UNIT_STRUCTURES_SPECIAL:
177
          case UNIT_DEFENCE:
178
            $levelGreen = floatval($ques[$planet['id']]['in_que'][que_get_unit_que($unit_id)][$user['id']][$planet['id']][$unit_id]);
179
          break;
180
181
          default:
182
          break;
183
        }
184
        $unitsPresentOrChanged = $unit_level_plain + abs($levelYellow) + abs($levelGreen);
185
186
        $unit_count += $unit_level_plain;
187
        $unit_count_abs += $unitsPresentOrChanged;
188
189
        $block_vars[] = [
190
          'ID'                     => $planet['id'],
191
          'TYPE'                   => $planet['planet_type'],
192
          'LEVEL'                  => $unitsPresentOrChanged ? $unit_level_plain : '-',
193
          'LEVEL_PLUS_YELLOW'      => $levelYellow,
194
          'LEVEL_PLUS_GREEN'       => $levelGreen,
195
          'LEVEL_TEXT'             => $unitsPresentOrChanged ? HelperString::numberFloorAndFormat($unit_level_plain) : '-',
196
          'LEVEL_PLUS_YELLOW_TEXT' => tplPrettyPlus($levelYellow),
197
          'LEVEL_PLUS_GREEN_TEXT'  => tplPrettyPlus($levelGreen),
198
          'PERCENT'                => $unit_is_factory ? ($unit_level_plain ? $planet[pname_factory_production_field_name($unit_id)] * 10 : -1) : -1,
199
          'FACTORY'                => $unit_is_factory,
200
        ];
201
      }
202
203
      if ($unit_count_abs) {
204
        $this->tplRenderUnitLine($template, $unit_id, $block_vars, $unit_count, $unit_is_factory);
205
      }
206
    }
207
  }
208
209
  /**
210
   * Renders line of unit for each planet
211
   *
212
   * @param template $template
213
   * @param int      $unit_id
214
   * @param array    $block_vars
215
   * @param int      $unit_count
216
   * @param bool     $unit_is_factory
217
   *
218
   */
219
  protected function tplRenderUnitLine($template, $unit_id, $block_vars, $unit_count, $unit_is_factory) {
220
    // Adding unit cell name
221
    $template->assign_block_vars('prods', [
222
      'ID'    => $unit_id,
223
      'FIELD' => 'unit_' . $unit_id, // TODO Делать это прямо в темплейте
224
      'NAME'  => $this->lang['tech'][$unit_id],
225
      'MODE'  => static::GROUPS_TO_NAMES[get_unit_param($unit_id, P_UNIT_TYPE)],
226
    ]);
227
228
    $imperiumYellows = [];
229
    $imperiumGreens = [];
230
    // Adding data for each planet for this unit
231
    foreach ($block_vars as $block_var) {
232
      $imperiumYellows[$unit_id] += $block_var['LEVEL_PLUS_YELLOW'];
233
      $imperiumGreens[$unit_id] += $block_var['LEVEL_PLUS_GREEN'];
234
      $template->assign_block_vars('prods.planet', $block_var);
235
    }
236
237
    // Adding final cell with Imperium total stat about this unit
238
    $template->assign_block_vars('prods.planet', [
239
      'ID'                     => 0,
240
      'LEVEL'                  => $unit_count,
241
      'LEVEL_TEXT'             => HelperString::numberFloorAndFormat($unit_count),
242
      'LEVEL_PLUS_YELLOW'      => $imperiumYellows[$unit_id],
243
      'LEVEL_PLUS_GREEN'       => $imperiumGreens[$unit_id],
244
      'LEVEL_PLUS_YELLOW_TEXT' => $imperiumYellows[$unit_id] == 0 ? '' : tplPrettyPlus($imperiumYellows[$unit_id]),
245
      'LEVEL_PLUS_GREEN_TEXT'  => $imperiumGreens[$unit_id] == 0 ? '' : tplPrettyPlus($imperiumGreens[$unit_id]),
246
      'PERCENT'                => $unit_is_factory ? '' : -1,
247
      'FACTORY'                => $unit_is_factory,
248
    ]);
249
  }
250
251
  /**
252
   * @param array[] $planets
253
   * @param array   $fleets
254
   *
255
   * @return array[][]
256
   */
257
  protected function tplRenderPlanets(&$planets, $fleets) {
258
    $result = [];
259
260
    $planet_density = sn_get_groups('planet_density');
261
262
    foreach ($planets as $planetId => $planet) {
263
      $templatizedPlanet = tpl_parse_planet($planet);
264
//      $planet['BUILDING_ID'] = $templatizedPlanet['BUILDING_ID'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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
//      $planet['hangar_que'] = $templatizedPlanet['hangar_que'];
266
//      $planet['full_que'] = $templatizedPlanet;
267
268
      $fleet_list = $fleets[$planetId];
269
      foreach ([RES_METAL, RES_CRYSTAL, RES_DEUTERIUM] as $resourceId) {
270
        if (empty($fleet_list['own']['total'][$resourceId])) {
271
          $templatizedPlanet['RES_' . $resourceId] = 0;
272
        } else {
273
          $templatizedPlanet['RES_' . $resourceId] = $fleet_list['own']['total'][$resourceId];
274
          $templatizedPlanet['RES_' . $resourceId . '_TEXT'] = HelperString::numberFloorAndFormat($fleet_list['own']['total'][$resourceId]);
275
        }
276
      }
277
      $templatizedPlanet += tpl_parse_planet_result_fleet($planet, $fleet_list);
278
279
      $templatizedPlanet += [
280
        'METAL_CUR'  => prettyNumberStyledCompare($planet['metal'], $planet['metal_max']),
281
        'METAL_PROD' => HelperString::numberFloorAndFormat($planet['metal_perhour']),
282
283
        'CRYSTAL_CUR'  => prettyNumberStyledCompare($planet['crystal'], $planet['crystal_max']),
284
        'CRYSTAL_PROD' => HelperString::numberFloorAndFormat($planet['crystal_perhour']),
285
286
        'DEUTERIUM_CUR'  => prettyNumberStyledCompare($planet['deuterium'], $planet['deuterium_max']),
287
        'DEUTERIUM_PROD' => HelperString::numberFloorAndFormat($planet['deuterium_perhour']),
288
289
        'ENERGY_CUR' => prettyNumberStyledDefault($planet['energy_max'] - $planet['energy_used']),
290
        'ENERGY_MAX' => HelperString::numberFloorAndFormat($planet['energy_max']),
291
292
        'TEMP_MIN' => $planet['temp_min'],
293
        'TEMP_MAX' => $planet['temp_max'],
294
295
        'DENSITY_CLASS'      => $planet['density_index'],
296
        'DENSITY_RICHNESS'   => $planet_density[$planet['density_index']][UNIT_PLANET_DENSITY_RICHNESS],
297
        'DENSITY_CLASS_TEXT' => $this->lang['uni_planet_density_types'][$planet['density_index']],
298
      ];
299
300
      $result[] = $templatizedPlanet;
301
    }
302
303
    return [
304
      '.' => [
305
        'planet' => $result
306
      ]
307
    ];
308
  }
309
310
  /**
311
   * @param array $fleets
312
   *
313
   * @return array
314
   */
315
  protected function tplRenderFleets($fleets) {
316
    $fleetsRendered = [];
317
    foreach ($fleets as $planetId => $fleet_list) {
318
      if (!empty($fleet_list['own']['count'])) {
319
        $fleetsRendered[$planet['id']] = tpl_parse_fleet_sn($fleet_list['own']['total'], getUniqueFleetId(['id' => $planetId]));
320
      }
321
    }
322
323
    return tpl_assign_fleet_generate($fleetsRendered);
324
  }
325
326
  /**
327
   * @param array[] $planets
328
   *
329
   * @return array
330
   */
331
  protected function fleetGetFlyingToPlanets(&$planets) {
332
    $fleets = [];
333
    foreach ($planets as $planetId => &$planet) {
334
      $fleets[$planet['id']] = flt_get_fleets_to_planet($planet);
335
    }
336
337
    return $fleets;
338
  }
339
340
  /**
341
   * @param template $template
342
   * @param array    $planets
343
   */
344
  function tplTotalPlanetInfo($template, $planets) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
345
    $imperiumStats = [
346
      'temp_min' => 1000,
347
      'temp_max' => -999,
348
    ];
349
350
    foreach ($planets as $planetId => &$planet) {
351
      $imperiumStats['fields'] += $planet['field_current'];
352
      $imperiumStats['metal'] += $planet['metal'];
353
      $imperiumStats['crystal'] += $planet['crystal'];
354
      $imperiumStats['deuterium'] += $planet['deuterium'];
355
      $imperiumStats['energy'] += $planet['energy_max'] - $planet['energy_used'];
356
357
      $imperiumStats['fields_max'] += eco_planet_fields_max($planet);
358
      $imperiumStats['metal_perhour'] += $planet['metal_perhour'];
359
      $imperiumStats['crystal_perhour'] += $planet['crystal_perhour'];
360
      $imperiumStats['deuterium_perhour'] += $planet['deuterium_perhour'];
361
      $imperiumStats['energy_max'] += $planet['energy_max'];
362
363
      $imperiumStats['temp_min'] = min($planet['temp_min'], $imperiumStats['temp_min']);
364
      $imperiumStats['temp_max'] = max($planet['temp_max'], $imperiumStats['temp_max']);
365
    }
366
367
    $template->assign_block_vars('planet', array_merge([
368
      'ID'   => 0,
369
      'NAME' => $this->lang['sys_total'],
370
371
      'FIELDS_CUR' => $imperiumStats['fields'],
372
      'FIELDS_MAX' => $imperiumStats['fields_max'],
373
374
      'METAL_CUR'  => HelperString::numberFloorAndFormat($imperiumStats['metal']),
375
      'METAL_PROD' => HelperString::numberFloorAndFormat($imperiumStats['metal_perhour']),
376
377
      'CRYSTAL_CUR'  => HelperString::numberFloorAndFormat($imperiumStats['crystal']),
378
      'CRYSTAL_PROD' => HelperString::numberFloorAndFormat($imperiumStats['crystal_perhour']),
379
380
      'DEUTERIUM_CUR'  => HelperString::numberFloorAndFormat($imperiumStats['deuterium']),
381
      'DEUTERIUM_PROD' => HelperString::numberFloorAndFormat($imperiumStats['deuterium_perhour']),
382
383
      'ENERGY_CUR' => HelperString::numberFloorAndFormat($imperiumStats['energy']),
384
      'ENERGY_MAX' => HelperString::numberFloorAndFormat($imperiumStats['energy_max']),
385
386
      'TEMP_MIN' => $imperiumStats['temp_min'],
387
      'TEMP_MAX' => $imperiumStats['temp_max'],
388
    ]));
389
  }
390
391
  /**
392
   * @param array    $user
393
   * @param template $template
394
   */
395
  protected function tplAddGlobals(&$user, $template) {
396
    $template->assign_vars([
397
      'COLONIES_CURRENT' => get_player_current_colonies($user),
398
      'COLONIES_MAX'     => get_player_max_colonies($user),
399
400
      'EXPEDITIONS_CURRENT' => fleet_count_flying($user['id'], MT_EXPLORE),
401
      'EXPEDITIONS_MAX'     => get_player_max_expeditons($user),
402
403
      'PLANET_DENSITY_RICHNESS_NORMAL'  => PLANET_DENSITY_RICHNESS_NORMAL,
404
      'PLANET_DENSITY_RICHNESS_AVERAGE' => PLANET_DENSITY_RICHNESS_AVERAGE,
405
      'PLANET_DENSITY_RICHNESS_GOOD'    => PLANET_DENSITY_RICHNESS_GOOD,
406
      'PLANET_DENSITY_RICHNESS_PERFECT' => PLANET_DENSITY_RICHNESS_PERFECT,
407
408
      'PAGE_HEADER' => $this->lang['imp_overview'],
409
    ]);
410
  }
411
412
}
413