Issues (1369)

classes/Pages/Deprecated/PageImperium.php (6 issues)

1
<?php
2
/**
3
 * Created by Gorlum 01.10.2017 17:53
4
 */
5
6
namespace Pages\Deprecated;
7
8
use DBAL\db_mysql;
9
use Fleet\DbFleetStatic;
10
use SN;
11
use SnTemplate;
12
use \template;
0 ignored issues
show
The type \template was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use \classLocale;
0 ignored issues
show
The type \classLocale was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use Planet\DBStaticPlanet;
15
use \HelperString;
0 ignored issues
show
The type \HelperString was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
17
class PageImperium {
18
19
  const GROUPS_TO_NAMES = [
20
    UNIT_STRUCTURES         => 'structures',
21
    UNIT_STRUCTURES_SPECIAL => 'structures',
22
    UNIT_SHIPS              => 'fleet',
23
    UNIT_DEFENCE            => 'defense',
24
  ];
25
26
  /**
27
   * @var classLocale $lang ;
28
   */
29
  protected $lang;
30
31
32
  /**
33
   * @param template|null $template
34
   */
35
  public static function viewStatic(template $template = null) {
36
    $that = new static();
37
38
    $template = $that->view($template);
39
    unset($that);
40
41
    return $template;
42
  }
43
44
  /**
45
   * @param template|null $template
46
   */
47
  public static function modelStatic(template $template = null) {
48
    $that = new static();
49
50
    $that->modelAdjustMinePercent();
51
    unset($that);
52
53
    return $template;
54
  }
55
56
  public function __construct() {
57
    global $lang;
58
    $this->lang = $lang;
59
  }
60
61
  /**
62
   * @param template|null $template
63
   *
64
   * @return template
65
   */
66
  public function view(template $template = null) {
67
    global $user;
68
69
    list($planets, $ques) = $this->getUpdatedUserPlanetsAndQues($user);
70
    $fleets = $this->fleetGetFlyingToPlanets($planets);
71
72
    $template = SnTemplate::gettemplate('imperium', $template);
73
74
    $template->assign_recursive(templateFillPercent());
75
76
    $template->assign_recursive($this->tplRenderPlanets($user, $planets, $fleets));
77
    $template->assign_recursive($this->tplRenderFleets($planets, $fleets));
78
    $this->tplTotalPlanetInfo($template, $planets);
79
80
    foreach (self::GROUPS_TO_NAMES as $unit_group_id => $internalGroupName) {
81
      $template->assign_block_vars('prods', array(
82
        'NAME' => $this->lang['tech'][$unit_group_id],
83
      ));
84
      $this->imperiumTemplatizeUnitGroup($user, $template, $unit_group_id, $planets, $ques, $fleets);
85
    }
86
87
    $template->assign_var('amount', count($planets) + 2);
88
    $this->tplAddGlobals($user, $template);
89
90
    return $template;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $template returns the type template which is incompatible with the documented return type \template.
Loading history...
91
  }
92
93
  /**
94
   * Store current mines load in DB
95
   */
96
  protected function modelAdjustMinePercent() {
97
    global $user;
98
99
    if (!sys_get_param('save_production') || !is_array($production = sys_get_param('percent')) || empty($production)) {
100
      return;
101
    }
102
103
    $sn_group_factories = sn_get_groups('factories');
104
105
    foreach (DBStaticPlanet::db_planet_list_sorted($user, false) as $planetId => $planet) {
106
      $query = [];
107
      foreach ($sn_group_factories as $factory_unit_id) {
108
        $unit_db_name_porcent = pname_factory_production_field_name($factory_unit_id);
109
        if (
110
          // Changes required to mine production
111
          isset($production[$factory_unit_id][$planet['id']])
112
          // If mine is managed
113
          && get_unit_param($factory_unit_id, P_MINING_IS_MANAGED)
114
          // Input value is valid
115
          && ($actual_porcent = intval($production[$factory_unit_id][$planet['id']] / 10)) >= 0
116
          && $actual_porcent <= 10
117
          // And changes really should be stored to DB
118
          && $actual_porcent != $planet[$unit_db_name_porcent]
119
        ) {
120
          $actual_porcent = intval($actual_porcent);
121
          $query[] = "`{$unit_db_name_porcent}` = {$actual_porcent}";
122
        }
123
      }
124
125
      if (!empty($query)) {
126
        DBStaticPlanet::db_planet_set_by_id($planet['id'], implode(',', $query));
127
      }
128
    }
129
  }
130
131
  /**
132
   * @param array $user
133
   *
134
   * @return array[]
135
   */
136
  protected function getUpdatedUserPlanetsAndQues($user) {
137
    $planets = array();
138
    $ques = array();
139
    $planet_row_list = DBStaticPlanet::db_planet_list_sorted($user);
140
    foreach ($planet_row_list as $planet) {
141
      db_mysql::db_transaction_start();
142
      $global_data = sys_o_get_updated($user['id'], $planet['id'], SN_TIME_NOW, false, true);
143
      $planets[$planet['id']] = $global_data['planet'];
144
      $ques[$planet['id']] = $global_data['que'];
145
      db_mysql::db_transaction_commit();
146
    }
147
148
    return array($planets, $ques);
149
  }
150
151
  /**
152
   * @param array    $user
153
   * @param template $template
154
   * @param int      $unit_group_id
155
   * @param array[]  $planets
156
   * @param array[]  $ques
157
   * @param array    $fleets
158
   */
159
  protected function imperiumTemplatizeUnitGroup(&$user, $template, $unit_group_id, $planets, $ques, $fleets) {
160
    $sn_group_factories = sn_get_groups('factories');
161
162
    foreach (get_unit_param('techtree', $unit_group_id) as $unit_id) {
163
      $unit_count = $unit_count_abs = 0;
164
      $block_vars = array();
165
      $unit_is_factory = in_array($unit_id, $sn_group_factories) && get_unit_param($unit_id, P_MINING_IS_MANAGED);
166
      foreach ($planets as $planet) {
167
        $unit_level_plain = mrc_get_level($user, $planet, $unit_id, false, true);
168
169
        $levelGreen = 0;
170
        $levelYellow = 0;
171
172
        switch ($unit_group_id) {
173
          /** @noinspection PhpMissingBreakStatementInspection */
174
          case UNIT_SHIPS:
175
            $levelYellow = !empty($fleets[$planet['id']]['own']['total'][$unit_id]) ? floatval($fleets[$planet['id']]['own']['total'][$unit_id]) : 0;
176
177
          case UNIT_STRUCTURES:
178
          case UNIT_STRUCTURES_SPECIAL:
179
          case UNIT_DEFENCE:
180
            $levelGreen = floatval($ques[$planet['id']]['in_que'][que_get_unit_que($unit_id)][$user['id']][$planet['id']][$unit_id]);
181
          break;
182
183
          default:
184
          break;
185
        }
186
        $unitsPresentOrChanged = $unit_level_plain + abs($levelYellow) + abs($levelGreen);
187
188
        $unit_count += $unit_level_plain;
189
        $unit_count_abs += $unitsPresentOrChanged;
190
191
        $block_vars[] = [
192
          'ID'                     => $planet['id'],
193
          'TYPE'                   => $planet['planet_type'],
194
          'LEVEL'                  => $unitsPresentOrChanged ? $unit_level_plain : '-',
195
          'LEVEL_PLUS_YELLOW'      => $levelYellow,
196
          'LEVEL_PLUS_GREEN'       => $levelGreen,
197
          'LEVEL_TEXT'             => $unitsPresentOrChanged ? HelperString::numberFloorAndFormat($unit_level_plain) : '-',
198
          'LEVEL_PLUS_YELLOW_TEXT' => SnTemplate::tplPrettyPlus($levelYellow),
199
          'LEVEL_PLUS_GREEN_TEXT'  => SnTemplate::tplPrettyPlus($levelGreen),
200
          'PERCENT'                => $unit_is_factory ? ($unit_level_plain ? $planet[pname_factory_production_field_name($unit_id)] * 10 : -1) : -1,
201
          'FACTORY'                => $unit_is_factory,
202
        ];
203
      }
204
205
      if ($unit_count_abs) {
206
        $this->tplRenderUnitLine($template, $unit_id, $block_vars, $unit_count, $unit_is_factory);
0 ignored issues
show
It seems like $unit_count can also be of type double; however, parameter $unit_count of Pages\Deprecated\PageImperium::tplRenderUnitLine() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

206
        $this->tplRenderUnitLine($template, $unit_id, $block_vars, /** @scrutinizer ignore-type */ $unit_count, $unit_is_factory);
Loading history...
207
      }
208
    }
209
  }
210
211
  /**
212
   * Renders line of unit for each planet
213
   *
214
   * @param template $template
215
   * @param int      $unit_id
216
   * @param array    $block_vars
217
   * @param int      $unit_count
218
   * @param bool     $unit_is_factory
219
   *
220
   */
221
  protected function tplRenderUnitLine($template, $unit_id, $block_vars, $unit_count, $unit_is_factory) {
222
    // Adding unit cell name
223
    $template->assign_block_vars('prods', [
224
      'ID'    => $unit_id,
225
      'FIELD' => 'unit_' . $unit_id, // TODO Делать это прямо в темплейте
226
      'NAME'  => $this->lang['tech'][$unit_id],
227
      'MODE'  => static::GROUPS_TO_NAMES[get_unit_param($unit_id, P_UNIT_TYPE)],
228
    ]);
229
230
    $imperiumYellows = [];
231
    $imperiumGreens = [];
232
    // Adding data for each planet for this unit
233
    foreach ($block_vars as $block_var) {
234
      $imperiumYellows[$unit_id] += $block_var['LEVEL_PLUS_YELLOW'];
235
      $imperiumGreens[$unit_id] += $block_var['LEVEL_PLUS_GREEN'];
236
      $template->assign_block_vars('prods.planet', $block_var);
237
    }
238
239
    // Adding final cell with Imperium total stat about this unit
240
    $template->assign_block_vars('prods.planet', [
241
      'ID'                     => 0,
242
      'LEVEL'                  => $unit_count,
243
      'LEVEL_TEXT'             => HelperString::numberFloorAndFormat($unit_count),
244
      'LEVEL_PLUS_YELLOW'      => $imperiumYellows[$unit_id],
245
      'LEVEL_PLUS_GREEN'       => $imperiumGreens[$unit_id],
246
      'LEVEL_PLUS_YELLOW_TEXT' => $imperiumYellows[$unit_id] == 0 ? '' : SnTemplate::tplPrettyPlus($imperiumYellows[$unit_id]),
247
      'LEVEL_PLUS_GREEN_TEXT'  => $imperiumGreens[$unit_id] == 0 ? '' : SnTemplate::tplPrettyPlus($imperiumGreens[$unit_id]),
248
      'PERCENT'                => $unit_is_factory ? '' : -1,
249
      'FACTORY'                => $unit_is_factory,
250
    ]);
251
  }
252
253
  /**
254
   * @param array[] $planets
255
   * @param array   $fleets
256
   *
257
   * @return array[][]
258
   */
259
  protected function tplRenderPlanets($user, &$planets, $fleets) {
260
    $result = [];
261
262
    $planet_density = sn_get_groups('planet_density');
263
264
    foreach ($planets as $planetId => $planet) {
265
      $templatizedPlanet = tpl_parse_planet($user, $planet);
266
267
      if($planet['planet_type'] == PT_MOON) {
268
        $parentPlanet = DBStaticPlanet::db_planet_by_id($planet['parent_planet']);
269
      } else {
270
        $parentPlanet = $planet;
271
      }
272
273
      $fleet_list = $fleets[$planetId];
274
      foreach ([RES_METAL, RES_CRYSTAL, RES_DEUTERIUM] as $resourceId) {
275
        if (empty($fleet_list['own']['total'][$resourceId])) {
276
          $templatizedPlanet['RES_' . $resourceId] = 0;
277
        } else {
278
          $templatizedPlanet['RES_' . $resourceId] = $fleet_list['own']['total'][$resourceId];
279
          $templatizedPlanet['RES_' . $resourceId . '_TEXT'] = HelperString::numberFloorAndFormat($fleet_list['own']['total'][$resourceId]);
280
        }
281
      }
282
      $templatizedPlanet += tpl_parse_planet_result_fleet($planet, $fleet_list);
283
284
      $templatizedPlanet += [
285
        'METAL_CUR'  => prettyNumberStyledCompare($planet['metal'], $planet['metal_max']),
286
        'METAL_PROD_TEXT' => HelperString::numberFloorAndFormat($planet['metal_perhour']),
287
288
        'CRYSTAL_CUR'  => prettyNumberStyledCompare($planet['crystal'], $planet['crystal_max']),
289
        'CRYSTAL_PROD_TEXT' => HelperString::numberFloorAndFormat($planet['crystal_perhour']),
290
291
        'DEUTERIUM_CUR'  => prettyNumberStyledCompare($planet['deuterium'], $planet['deuterium_max']),
292
        'DEUTERIUM_PROD_TEXT' => HelperString::numberFloorAndFormat($planet['deuterium_perhour']),
293
294
        'ENERGY_CUR' => $planet['energy_max'] - $planet['energy_used'],
295
        'ENERGY_MAX' => $planet['energy_max'],
296
297
        'TEMP_MIN' => $planet['temp_min'],
298
        'TEMP_MAX' => $planet['temp_max'],
299
300
        'DENSITY_CLASS'      => $planet['density_index'],
301
        'DENSITY_RICHNESS'   => $planet_density[$planet['density_index']][UNIT_PLANET_DENSITY_RICHNESS],
302
        'DENSITY_CLASS_TEXT' => $this->lang['uni_planet_density_types'][$planet['density_index']],
303
304
        '_PARENT_PLANET' => &$parentPlanet,
305
      ];
306
307
      $templatizedPlanet['IS_CAPITAL'] = $parentPlanet['id'] == $user['id_planet'];
308
309
      $result[] = $templatizedPlanet;
310
    }
311
312
    return [
313
      '.' => [
314
        'planet' => $result
315
      ]
316
    ];
317
  }
318
319
  /**
320
   * @param array[] $planets
321
   * @param array[] $fleets
322
   *
323
   * @return array
324
   */
325
  protected function tplRenderFleets($planets, $fleets) {
326
    $fleetsRendered = [];
327
    foreach ($fleets as $planetId => $fleet_list) {
328
      if (!empty($fleet_list['own']['count'])) {
329
        $fleetsRendered[$planets[$planetId]['id']] = tpl_parse_fleet_sn($fleet_list['own']['total'], getUniqueFleetId(['id' => $planetId]));
330
      }
331
    }
332
333
    return tpl_assign_fleet_generate($fleetsRendered);
334
  }
335
336
  /**
337
   * @param array[] $planets
338
   *
339
   * @return array
340
   */
341
  protected function fleetGetFlyingToPlanets(&$planets) {
342
    $fleets = [];
343
    foreach ($planets as $planetId => &$planet) {
344
      $fleets[$planet['id']] = flt_get_fleets_to_planet($planet);
345
    }
346
347
    return $fleets;
348
  }
349
350
  /**
351
   * @param template $template
352
   * @param array    $planets
353
   */
354
  function tplTotalPlanetInfo($template, $planets) {
0 ignored issues
show
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...
355
    $imperiumStats = [
356
      'temp_min' => 1000,
357
      'temp_max' => -999,
358
    ];
359
360
    foreach ($planets as $planetId => &$planet) {
361
      $imperiumStats['fields'] += $planet['field_current'];
362
      $imperiumStats['metal'] += $planet['metal'];
363
      $imperiumStats['crystal'] += $planet['crystal'];
364
      $imperiumStats['deuterium'] += $planet['deuterium'];
365
      $imperiumStats['energy'] += $planet['energy_max'] - $planet['energy_used'];
366
367
      $imperiumStats['fields_max'] += eco_planet_fields_max($planet);
368
      $imperiumStats['metal_perhour'] += $planet['metal_perhour'];
369
      $imperiumStats['crystal_perhour'] += $planet['crystal_perhour'];
370
      $imperiumStats['deuterium_perhour'] += $planet['deuterium_perhour'];
371
      $imperiumStats['energy_max'] += $planet['energy_max'];
372
373
      $imperiumStats['temp_min'] = min($planet['temp_min'], $imperiumStats['temp_min']);
374
      $imperiumStats['temp_max'] = max($planet['temp_max'], $imperiumStats['temp_max']);
375
    }
376
377
    $template->assign_block_vars('planet', array_merge([
378
      'ID'   => 0,
379
      'NAME' => $this->lang['sys_total'],
380
381
      'FIELDS_CUR' => $imperiumStats['fields'],
382
      'FIELDS_MAX' => $imperiumStats['fields_max'],
383
384
      'METAL_CUR'  => HelperString::numberFloorAndFormat($imperiumStats['metal']),
385
      'METAL_PROD_TEXT' => HelperString::numberFloorAndFormat($imperiumStats['metal_perhour']),
386
387
      'CRYSTAL_CUR'  => HelperString::numberFloorAndFormat($imperiumStats['crystal']),
388
      'CRYSTAL_PROD_TEXT' => HelperString::numberFloorAndFormat($imperiumStats['crystal_perhour']),
389
390
      'DEUTERIUM_CUR'  => HelperString::numberFloorAndFormat($imperiumStats['deuterium']),
391
      'DEUTERIUM_PROD_TEXT' => HelperString::numberFloorAndFormat($imperiumStats['deuterium_perhour']),
392
393
      'ENERGY_CUR' => $imperiumStats['energy'],
394
      'ENERGY_MAX' => $imperiumStats['energy_max'],
395
396
      'TEMP_MIN' => $imperiumStats['temp_min'],
397
      'TEMP_MAX' => $imperiumStats['temp_max'],
398
    ]));
399
  }
400
401
  /**
402
   * @param array    $user
403
   * @param template $template
404
   */
405
  protected function tplAddGlobals(&$user, $template) {
406
    $template->assign_vars([
407
      'COLONIES_CURRENT' => get_player_current_colonies($user),
408
      'COLONIES_MAX'     => get_player_max_colonies($user),
409
410
      'EXPEDITIONS_CURRENT' => DbFleetStatic::fleet_count_flying($user['id'], MT_EXPLORE),
411
      'EXPEDITIONS_MAX'     => get_player_max_expeditons($user),
412
413
      'PLANET_DENSITY_RICHNESS_NORMAL'  => PLANET_DENSITY_RICHNESS_NORMAL,
414
      'PLANET_DENSITY_RICHNESS_AVERAGE' => PLANET_DENSITY_RICHNESS_AVERAGE,
415
      'PLANET_DENSITY_RICHNESS_GOOD'    => PLANET_DENSITY_RICHNESS_GOOD,
416
      'PLANET_DENSITY_RICHNESS_PERFECT' => PLANET_DENSITY_RICHNESS_PERFECT,
417
418
      'PAGE_HEADER' => $this->lang['imp_overview'],
419
    ]);
420
  }
421
422
}
423