Completed
Push — trunk ( 0e7a2e...6a6c5e )
by SuperNova.WS
07:28
created

PageFleet5Gathering::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by Gorlum 30.09.2017 11:01
4
 */
5
6
namespace Pages\Deprecated;
7
8
use Planet\DBStaticPlanet;
9
use \HelperString;
10
11
class PageFleet5Gathering {
12
13
  /**
14
   * @var \classLocale $lang
15
   */
16
  protected $lang;
17
18
  /**
19
   * @var float[] $infoTransportCapacity
20
   */
21
  protected $infoTransportCapacity;
22
23
  public function __construct() {
24
    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...
25
26
    $this->lang = $lang;
27
    $this->infoTransportCapacity = $this->getTransportUnitsCapacity();
28
  }
29
30
  /**
31
   * @param array     $user
32
   * @param array     $planetCurrent
33
   * @param float[][] $resources_taken - [int|string $planetId][int $resourceId] => float $resourceAmount
34
   *
35
   * @return array
36
   */
37
  public function flt_build_gathering(&$user, &$planetCurrent, $resources_taken = []) {
38
    // Caching sn_data names for quick access
39
    $planet_list = [];
40
41
    $takeAllResources = !is_array($resources_taken) || empty($resources_taken);
0 ignored issues
show
introduced by
The condition is_array($resources_taken) is always true.
Loading history...
42
    if ($takeAllResources) {
43
      $query = '';
44
    } else {
45
      $query = implode(',', array_keys($resources_taken));
46
      $query = " AND `destruyed` = 0 AND `id` IN ({$query})";
47
    }
48
49
    $planets_db_list = DBStaticPlanet::db_planet_list_sorted($user, $planetCurrent['id'], '*', $query);
50
    !is_array($planets_db_list) ? $planets_db_list = [] : false;
0 ignored issues
show
introduced by
The condition is_array($planets_db_list) is always false.
Loading history...
51
52
    foreach ($planets_db_list as $planet_id => &$planetRecord) {
53
      // begin planet loop
54
      sn_db_transaction_start();
55
      // Вот тут надо посчитать - отработать очереди и выяснить, сколько ресов на каждой планете
56
      $planetRecord = sys_o_get_updated($user, $planetRecord, SN_TIME_NOW, true);
57
      $planetRecord = $planetRecord['planet'];
58
      sn_db_transaction_commit();
59
60
      if ($takeAllResources) {
61
        $resources_taken[$planet_id] = 1;
62
      }
63
64
      $planetResources = $this->calcPlanetResources($user, $resources_taken, $planetRecord);
65
      $fleetCapacityList = $this->calcFleetCapacity($user, $planetRecord);
66
      $fleetFullCapacity = array_sum($fleetCapacityList);
67
68
      $fleet = $this->calcShipAmount($fleetCapacityList, min($planetResources, $fleetFullCapacity));
69
70
      $result = ATTACK_NO_FLEET;
71
      $travel_data = null;
72
      if (!empty($fleet)) {
73
        $travel_data = flt_travel_data($user, $planetCurrent, $planetRecord, $fleet, 10);
74
75
        if (floor(mrc_get_level($user, $planetRecord, RES_DEUTERIUM, true)) >= $travel_data['consumption']) {
76
          $will_take = min($planetResources, $fleetFullCapacity) - $travel_data['consumption'];
77
78
          $this->fillFleetResources($user, $resources_taken, $planetRecord, $will_take, $fleet);
79
          $result = ATTACK_ALLOWED;
80
        } else {
81
          $result = ATTACK_NO_FUEL;
82
        }
83
      }
84
85
      $planet_list[$planet_id] =
86
        [
87
          'PLANET_DB_DATA' => $planetRecord,
88
          'ID'             => $planetRecord['id'],
89
          'NAME'           => $planetRecord['name'],
90
          'GALAXY'         => $planetRecord['galaxy'],
91
          'SYSTEM'         => $planetRecord['system'],
92
          'PLANET'         => $planetRecord['planet'],
93
          'TYPE'           => $planetRecord['planet_type'],
94
          'TYPE_PRINT'     => $this->lang['sys_planet_type'][$planetRecord['planet_type']],
95
          'METAL'          => floor($planetRecord['metal']),
96
          'CRYSTAL'        => floor($planetRecord['crystal']),
97
          'DEUTERIUM'      => floor($planetRecord['deuterium']),
98
          'METAL_TEXT'     => HelperString::numberFloorAndFormat($planetRecord['metal']),
99
          'CRYSTAL_TEXT'   => HelperString::numberFloorAndFormat($planetRecord['crystal']),
100
          'DEUTERIUM_TEXT' => HelperString::numberFloorAndFormat($planetRecord['deuterium']),
101
          'RESOURCES'      => $planetResources,
102
          'RESOURCES_TEXT' => HelperString::numberFloorAndFormat($planetResources),
103
104
          'FLEET'               => $fleet,
105
          'FLEET_CAPACITY'      => $fleetFullCapacity,
106
          'FLEET_CAPACITY_TEXT' => prettyNumberStyledCompare($fleetFullCapacity, -$planetResources),
107
108
          'RESULT' => $result,
109
//          'MESSAGE' => $this->lang['fl_attack_error'][$result],
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% 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...
110
        ]
111
        + (!empty($travel_data) ?
112
          [
113
            'FLEET_SPEED'   => $travel_data['fleet_speed'],
114
            'DISTANCE'      => $travel_data['distance'],
115
            'DURATION'      => $travel_data['duration'],
116
            'DURATION_TEXT' => $travel_data['duration'] ? pretty_time($travel_data['duration']) : $this->lang['flt_no_fuel'],
117
            'CONSUMPTION'   => $travel_data['consumption'],
118
          ]
119
          : []);
120
    } // end planet loop
121
122
    return $planet_list;
123
  }
124
125
  /**
126
   * @return array
127
   */
128
  protected function getTransportUnitsCapacity() {
129
    $transports = [];
130
    foreach (sn_get_groups('flt_transports') as $transport_id) {
131
      $transports[$transport_id] = get_unit_param($transport_id, P_CAPACITY);
132
    }
133
    arsort($transports);
134
135
    return $transports;
136
  }
137
138
  /**
139
   * @param array $user
140
   * @param array $resources_taken
141
   * @param array $planet_db_data
142
   *
143
   * @return float
144
   */
145
  protected function calcPlanetResources(&$user, $resources_taken, $planet_db_data) {
146
    $planet_resources = 0;
147
    foreach (sn_get_groups('resources_loot') as $resource_id) {
148
      if ($resources_taken[$planet_db_data['id']] == 1 || $resources_taken[$planet_db_data['id']][$resource_id] > 0) {
149
        $planet_resources += floor(mrc_get_level($user, $planet_db_data, $resource_id, true, true));
0 ignored issues
show
Bug introduced by
It seems like mrc_get_level($user, $pl...esource_id, true, true) can also be of type boolean; however, parameter $value of floor() does only seem to accept double, 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

149
        $planet_resources += floor(/** @scrutinizer ignore-type */ mrc_get_level($user, $planet_db_data, $resource_id, true, true));
Loading history...
150
      }
151
    }
152
153
    return $planet_resources;
154
  }
155
156
  /**
157
   * @param array $user
158
   * @param array $planet_db_data
159
   *
160
   * @return float[]
161
   */
162
  protected function calcFleetCapacity(&$user, $planet_db_data) {
163
    $fleetCapacityList = [];
164
    foreach ($this->infoTransportCapacity as $ship_id => $ship_capacity) {
165
      if (($ship_count = mrc_get_level($user, $planet_db_data, $ship_id, true, true)) > 0) {
166
        $fleetCapacityList[$ship_id] = $ship_count * $ship_capacity;
167
      }
168
    }
169
170
    return $fleetCapacityList;
171
  }
172
173
  /**
174
   * @param float[] $fleetCapacityList - List of capacities per ship
175
   * @param float   $maxResourcesToTake - Maximum resources that can be taken from this planet with whole transport fleet
176
   *
177
   * @return array
178
   */
179
  protected function calcShipAmount($fleetCapacityList, $maxResourcesToTake) {
180
    $fleet = [];
181
    foreach ($fleetCapacityList as $ship_id => $shipCapacity) {
182
      $can_take = min($maxResourcesToTake, $shipCapacity);
183
      if ($can_take <= 0) {
184
        continue;
185
      }
186
187
      $fleet[$ship_id] = ceil($can_take / $this->infoTransportCapacity[$ship_id]);
188
189
      $maxResourcesToTake -= $can_take;
190
      if ($maxResourcesToTake <= 0) {
191
        break;
192
      }
193
    }
194
195
    return $fleet;
196
  }
197
198
  /**
199
   * @param array $user
200
   * @param array $resources_taken
201
   * @param array $planetRecord
202
   * @param float $will_take
203
   * @param array $fleet
204
   */
205
  protected function fillFleetResources(&$user, $resources_taken, $planetRecord, $will_take, &$fleet) {
206
    foreach (sn_get_groups('resources_loot') as $resource_id) {
207
      if ($resources_taken[$planetRecord['id']] != 1 && !$resources_taken[$planetRecord['id']][$resource_id]) {
208
        continue;
209
      }
210
211
      $resource_amount = floor(mrc_get_level($user, $planetRecord, $resource_id, true, true));
0 ignored issues
show
Bug introduced by
It seems like mrc_get_level($user, $pl...esource_id, true, true) can also be of type boolean; however, parameter $value of floor() does only seem to accept double, 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

211
      $resource_amount = floor(/** @scrutinizer ignore-type */ mrc_get_level($user, $planetRecord, $resource_id, true, true));
Loading history...
212
213
      $fleet[$resource_id] = min($will_take, $resource_amount);
214
      $will_take -= $resource_amount;
215
216
      if ($will_take <= 0) {
217
        break;
218
      }
219
    }
220
  }
221
222
223
  /**
224
   * @param array     $user
225
   * @param array     $planetrow
226
   * @param \template $template
227
   */
228
  public function modelFleet5Gathering(&$user, &$planetrow, $template) {
229
    if (empty($resources_taken = sys_get_param('resources')) || !is_array($resources_taken)) {
230
      return;
231
    }
232
233
    $planet_list = $this->flt_build_gathering($user, $planetrow, $resources_taken);
234
235
    foreach ($planet_list as $planet_id => $planet_data) {
236
      if ($planet_data['RESULT'] == ATTACK_ALLOWED) {
237
        $planet_data['RESULT'] = flt_t_send_fleet($user, $planet_data['PLANET_DB_DATA'], $planetrow, $planet_data['FLEET'], MT_TRANSPORT);
238
      }
239
240
      $planet_data['MESSAGE'] = $this->lang['fl_attack_error'][$planet_data['RESULT']];
241
242
      $template->assign_block_vars('results', $planet_data);
243
      if (!empty($planet_data['FLEET']) && $planet_data['RESULT'] == ATTACK_ALLOWED) {
244
        foreach ($planet_data['FLEET'] as $unit_id => $amount) {
245
          $template->assign_block_vars('results.units', [
246
            'ID'     => $unit_id,
247
            'NAME'   => $this->lang['tech'][$unit_id],
248
            'AMOUNT' => $amount
249
          ]);
250
        }
251
      }
252
    }
253
  }
254
255
  /**
256
   * @param array     $user
257
   * @param array     $planetrow
258
   * @param \template $template
259
   */
260
  public function viewPage5Gathering(&$user, &$planetrow, $template) {
261
    $planet_list = $this->flt_build_gathering($user, $planetrow, []);
262
    foreach ($planet_list as $planet_data) {
263
//      $planet_data['DURATION'] = $planet_data['DURATION'] ? pretty_time($planet_data['DURATION']) : $this->lang['flt_no_fuel'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% 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...
264
      $template->assign_block_vars('colonies', $planet_data);
265
    }
266
267
    $template->assign_vars([
268
      'PAGE_HINT'      => $this->lang['fl_page5_hint'],
269
      'METAL_NEED'     => HelperString::numberFloorAndFormat(max(0, -sys_get_param_float('metal'))),
270
      'CRYSTAL_NEED'   => HelperString::numberFloorAndFormat(max(0, -sys_get_param_float('crystal'))),
271
      'DEUTERIUM_NEED' => HelperString::numberFloorAndFormat(max(0, -sys_get_param_float('deuterium'))),
272
    ]);
273
274
    tpl_set_resource_info($template, $planetrow, []);
275
276
    display($template, $this->lang['fl_title']);
277
  }
278
279
}
280