Completed
Push — work-fleets ( 8b8b7f...487af6 )
by SuperNova.WS
04:56
created

Fleet::RestoreFleetToPlanet()   C

Complexity

Conditions 16
Paths 67

Size

Total Lines 70
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 9
Bugs 1 Features 0
Metric Value
c 9
b 1
f 0
dl 0
loc 70
rs 5.5942
cc 16
eloc 33
nc 67
nop 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A Fleet::markReturnedAndSave() 0 4 1
B Fleet::unitsSetFromArray() 0 16 5
A Fleet::set_times() 0 7 3

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
/**
4
 * Class Fleet
5
 *
6
 * @property int dbId
7
 * @property int playerOwnerId
8
 * @property int group_id
9
 * @property int mission_type
10
 * @property int target_owner_id
11
 * @property int is_returning
12
 *
13
 * @property int time_launch
14
 * @property int time_arrive_to_target
15
 * @property int time_mission_job_complete
16
 * @property int time_return_to_source
17
 *
18
 * @property int fleet_start_planet_id
19
 * @property int fleet_start_galaxy
20
 * @property int fleet_start_system
21
 * @property int fleet_start_planet
22
 * @property int fleet_start_type
23
 *
24
 * @property int fleet_end_planet_id
25
 * @property int fleet_end_galaxy
26
 * @property int fleet_end_system
27
 * @property int fleet_end_planet
28
 * @property int fleet_end_type
29
 *
30
 */
31
class Fleet extends UnitContainer {
32
33
34
  // DBRow inheritance *************************************************************************************************
35
36
  /**
37
   * Table name in DB
38
   *
39
   * @var string
40
   */
41
  protected static $_table = 'fleets';
42
  /**
43
   * Name of ID field in DB
44
   *
45
   * @var string
46
   */
47
  protected static $_dbIdFieldName = 'fleet_id';
48
  /**
49
   * DB_ROW to Class translation scheme
50
   *
51
   * @var array
52
   */
53
  protected static $_properties = array(
54
    'dbId'          => array(
55
      P_DB_FIELD => 'fleet_id',
56
    ),
57
    'playerOwnerId' => array(
58
      P_DB_FIELD => 'fleet_owner',
59
    ),
60
    'mission_type'  => array(
61
      P_DB_FIELD   => 'fleet_mission',
62
      P_FUNC_INPUT => 'intval',
63
    ),
64
65
    'target_owner_id' => array(
66
      P_DB_FIELD => 'fleet_target_owner',
67
    ),
68
    'group_id'        => array(
69
      P_DB_FIELD => 'fleet_group',
70
    ),
71
    'is_returning'    => array(
72
      P_DB_FIELD   => 'fleet_mess',
73
      P_FUNC_INPUT => 'intval',
74
    ),
75
76
    'shipCount' => array(
77
      P_DB_FIELD  => 'fleet_amount',
78
// TODO - CHECK !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% 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...
79
//      P_FUNC_OUTPUT => 'get_ship_count',
80
//      P_DB_FIELDS_LINKED => array(
81
//        'fleet_amount',
82
//      ),
83
      P_READ_ONLY => true,
84
    ),
85
86
    'time_launch' => array(
87
      P_DB_FIELD => 'start_time',
88
    ),
89
90
91
    'time_arrive_to_target'     => array(
92
      P_DB_FIELD => 'fleet_start_time',
93
    ),
94
    'time_mission_job_complete' => array(
95
      P_DB_FIELD => 'fleet_end_stay',
96
    ),
97
    'time_return_to_source'     => array(
98
      P_DB_FIELD => 'fleet_end_time',
99
    ),
100
101
    'fleet_start_planet_id' => array(
102
      P_DB_FIELD   => 'fleet_start_planet_id',
103
      P_FUNC_INPUT => 'nullIfEmpty',
104
    ),
105
106
107
    'fleet_start_galaxy' => array(
108
      P_DB_FIELD => 'fleet_start_galaxy',
109
    ),
110
    'fleet_start_system' => array(
111
      P_DB_FIELD => 'fleet_start_system',
112
    ),
113
    'fleet_start_planet' => array(
114
      P_DB_FIELD => 'fleet_start_planet',
115
    ),
116
    'fleet_start_type'   => array(
117
      P_DB_FIELD => 'fleet_start_type',
118
    ),
119
120
    'fleet_end_planet_id' => array(
121
      P_DB_FIELD   => 'fleet_end_planet_id',
122
      P_FUNC_INPUT => 'nullIfEmpty',
123
    ),
124
    'fleet_end_galaxy'    => array(
125
      P_DB_FIELD => 'fleet_end_galaxy',
126
    ),
127
    'fleet_end_system'    => array(
128
      P_DB_FIELD => 'fleet_end_system',
129
    ),
130
    'fleet_end_planet'    => array(
131
      P_DB_FIELD => 'fleet_end_planet',
132
    ),
133
    'fleet_end_type'      => array(
134
      P_DB_FIELD => 'fleet_end_type',
135
    ),
136
137
138
    'resource_list' => array(
139
      P_METHOD_EXTRACT   => 'resourcesExtract',
140
      P_METHOD_INJECT    => 'resourcesInject',
141
      P_DB_FIELDS_LINKED => array(
142
        'fleet_resource_metal',
143
        'fleet_resource_crystal',
144
        'fleet_resource_deuterium',
145
      ),
146
    ),
147
  );
148
149
150
  // UnitContainer inheritance *****************************************************************************************
151
  /**
152
   * Type of this location
153
   *
154
   * @var int $locationType
155
   */
156
  protected static $locationType = LOC_FLEET;
157
158
159
  // New properties ****************************************************************************************************
160
  /**
161
   * `fleet_owner`
162
   *
163
   * @var int
164
   */
165
  protected $_playerOwnerId = 0;
166
  /**
167
   * `fleet_group`
168
   *
169
   * @var int
170
   */
171
  protected $_group_id = 0;
172
173
  /**
174
   * `fleet_mission`
175
   *
176
   * @var int
177
   */
178
  protected $_mission_type = 0;
179
180
  /**
181
   * `fleet_target_owner`
182
   *
183
   * @var int
184
   */
185
  protected $_target_owner_id = null;
186
187
  /**
188
   * @var array
189
   */
190
  protected $resource_list = array(
191
    RES_METAL     => 0,
192
    RES_CRYSTAL   => 0,
193
    RES_DEUTERIUM => 0,
194
  );
195
196
197
  /**
198
   * `fleet__mess` - Флаг возвращающегося флота
199
   *
200
   * @var int
201
   */
202
  protected $_is_returning = 0;
203
  /**
204
   * `start_time` - Время отправления - таймштамп взлёта флота из точки отправления
205
   *
206
   * @var int $_time_launch
207
   */
208
  protected $_time_launch = 0; // `start_time` = SN_TIME_NOW
209
  /**
210
   * `fleet_start_time` - Время прибытия в точку миссии/время начала выполнения миссии
211
   *
212
   * @var int $_time_arrive_to_target
213
   */
214
  protected $_time_arrive_to_target = 0; // `fleet_start_time` = SN_TIME_NOW + $time_travel
215
  /**
216
   * `fleet_end_stay` - Время окончания миссии в точке назначения
217
   *
218
   * @var int $_time_mission_job_complete
219
   */
220
  protected $_time_mission_job_complete = 0; // `fleet_end_stay`
221
  /**
222
   * `fleet_end_time` - Время возвращения флота после окончания миссии
223
   *
224
   * @var int $_time_return_to_source
225
   */
226
  protected $_time_return_to_source = 0; // `fleet_end_time`
227
228
229
  protected $_fleet_start_planet_id = null;
230
  protected $_fleet_start_galaxy = 0;
231
  protected $_fleet_start_system = 0;
232
  protected $_fleet_start_planet = 0;
233
  protected $_fleet_start_type = PT_ALL;
234
235
  protected $_fleet_end_planet_id = null;
236
  protected $_fleet_end_galaxy = 0;
237
  protected $_fleet_end_system = 0;
238
  protected $_fleet_end_planet = 0;
239
  protected $_fleet_end_type = PT_ALL;
240
241
  // Missile properties
242
  public $missile_target = 0;
243
244
  // Fleet event properties
245
  public $fleet_start_name = '';
246
  public $fleet_end_name = '';
247
  public $ov_label = '';
248
  public $ov_this_planet = '';
249
  public $event_time = 0;
250
251
  protected $resource_delta = array();
252
  protected $resource_replace = array();
253
254
255
  /**
256
   * Returns location's player owner ID
257
   *
258
   * @return int
259
   */
260
  // TODO - REMOVE! TEMPORARY UNTIL THERE BE FULLLY FUNCTIONAL Player CLASS AND FLEETS WOULD BE LOCATED ON PLANET OR PLAYER!!!!!
261
  public function getPlayerOwnerId() {
262
    return $this->_dbId;
263
  }
264
265
  /**
266
   * Fleet constructor.
267
   */
268
  public function __construct() {
269
    parent::__construct();
270
  }
271
272
  public function isEmpty() {
273
    return !$this->resourcesGetTotal() && !$this->shipsGetTotal();
274
  }
275
276
//  public function getPlayerOwnerId() {
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% 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...
277
//    return $this->playerOwnerId;
278
//  }
279
280
  /**
281
   * Initializes Fleet from user params and posts it to DB
282
   */
283
  public function dbInsert() {
284
    // WARNING! MISSION TIMES MUST BE SET WITH set_times() method!
285
    // TODO - more checks!
286
    if(empty($this->_time_launch)) {
287
      die('Fleet time not set!');
288
    }
289
290
    parent::dbInsert();
291
  }
292
293
294
  /* FLEET DB ACCESS =================================================================================================*/
295
296
  /**
297
   * LOCK - Lock all records which can be used with mission
298
   *
299
   * @param $mission_data
300
   * @param $fleet_id
301
   *
302
   * @return array|bool|mysqli_result|null
303
   */
304
  public function dbLockFlying(&$mission_data) {
305
    // Тупо лочим всех юзеров, чьи флоты летят или улетают с координат отбытия/прибытия $fleet_row
306
    // Что бы делать это умно - надо учитывать fleet__mess во $fleet_row и в таблице fleets
307
308
    $fleet_id_safe = idval($this->_dbId);
309
310
    return doquery(
311
    // Блокировка самого флота
312
      "SELECT 1 FROM {{fleets}} AS f " .
313
314
      // Блокировка всех юнитов, принадлежащих этому флоту
315
      "LEFT JOIN {{unit}} as unit ON unit.unit_location_type = " . static::$locationType . " AND unit.unit_location_id = f.fleet_id " .
316
317
      // Блокировка всех прилетающих и улетающих флотов, если нужно
318
      // TODO - lock fleets by COORDINATES
319
      ($mission_data['dst_fleets'] ? "LEFT JOIN {{fleets}} AS fd ON fd.fleet_end_planet_id = f.fleet_end_planet_id OR fd.fleet_start_planet_id = f.fleet_end_planet_id " : '') .
320
      // Блокировка всех юнитов, принадлежащих прилетающим и улетающим флотам - ufd = unit_fleet_destination
321
      ($mission_data['dst_fleets'] ? "LEFT JOIN {{unit}} AS ufd ON ufd.unit_location_type = " . static::$locationType . " AND ufd.unit_location_id = fd.fleet_id " : '') .
322
323
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{users}} AS ud ON ud.id = f.fleet_target_owner " : '') .
324
      // Блокировка всех юнитов, принадлежащих владельцу планеты-цели
325
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS unit_player_dest ON unit_player_dest.unit_player_id = ud.id " : '') .
326
      // Блокировка планеты-цели
327
      ($mission_data['dst_planet'] ? "LEFT JOIN {{planets}} AS pd ON pd.id = f.fleet_end_planet_id " : '') .
328
      // Блокировка всех юнитов, принадлежащих планете-цели - НЕ НУЖНО. Уже залочили ранее, как принадлежащие игроку-цели
329
//      ($mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS upd ON upd.unit_location_type = " . LOC_PLANET . " AND upd.unit_location_id = pd.id " : '') .
330
331
332
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{users}} AS us ON us.id = f.fleet_owner " : '') .
333
      // Блокировка всех юнитов, принадлежащих владельцу флота
334
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS unit_player_src ON unit_player_src.unit_player_id = us.id " : '') .
335
      // Блокировка планеты отправления
336
      ($mission_data['src_planet'] ? "LEFT JOIN {{planets}} AS ps ON ps.id = f.fleet_start_planet_id " : '') .
337
      // Блокировка всех юнитов, принадлежащих планете с которой юниты были отправлены - НЕ НУЖНО. Уже залочили ранее, как принадлежащие владельцу флота
338
//      ($mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS ups ON ups.unit_location_type = " . LOC_PLANET . " AND ups.unit_location_id = ps.id " : '') .
339
340
      "WHERE f.fleet_id = {$fleet_id_safe} GROUP BY 1 FOR UPDATE"
341
    );
342
  }
343
344
345
  /* FLEET HELPERS =====================================================================================================*/
346
  /**
347
   * Forcibly returns fleet before time outs
348
   */
349
  public function commandReturn() {
350
    $ReturnFlyingTime = ($this->_time_mission_job_complete != 0 && $this->_time_arrive_to_target < SN_TIME_NOW ? $this->_time_arrive_to_target : SN_TIME_NOW) - $this->_time_launch + SN_TIME_NOW + 1;
351
352
    $this->markReturned();
353
354
    // Считаем, что флот уже долетел TODO
355
    $this->time_arrive_to_target = SN_TIME_NOW;
356
    // Убираем флот из группы
357
    $this->group_id = 0;
358
    // Отменяем работу в точке назначения
359
    $this->time_mission_job_complete = 0;
360
    // TODO - правильно вычслять время возвращения - по проделанному пути, а не по старому времени возвращения
361
    $this->time_return_to_source = $ReturnFlyingTime;
362
363
    // Записываем изменения в БД
364
    $this->dbSave();
365
366
    if($this->_group_id) {
367
      // TODO: Make here to delete only one AKS - by adding aks_fleet_count to AKS table
368
      db_fleet_aks_purge();
369
    }
370
  }
371
372
373
374
375
376
  /**
377
   * @return array
378
   */
379
  public function target_coordinates_without_type() {
380
    return array(
381
      'galaxy' => $this->_fleet_end_galaxy,
382
      'system' => $this->_fleet_end_system,
383
      'planet' => $this->_fleet_end_planet,
384
    );
385
  }
386
387
  /**
388
   * @return array
389
   */
390
  public function target_coordinates_typed() {
391
    return array(
392
      'galaxy' => $this->_fleet_end_galaxy,
393
      'system' => $this->_fleet_end_system,
394
      'planet' => $this->_fleet_end_planet,
395
      'type'   => $this->_fleet_end_type,
396
    );
397
  }
398
399
  /**
400
   * @return array
401
   */
402
  public function launch_coordinates_typed() {
403
    return array(
404
      'galaxy' => $this->_fleet_start_galaxy,
405
      'system' => $this->_fleet_start_system,
406
      'planet' => $this->_fleet_start_planet,
407
      'type'   => $this->_fleet_start_type,
408
    );
409
  }
410
411
412
413
  /**
414
   * Sets object fields for fleet return
415
   */
416
  public function markReturned() {
417
    // TODO - Проверка - а не возвращается ли уже флот?
418
    $this->is_returning = 1;
419
  }
420
421
  public function isReturning() {
422
    return 1 == $this->_is_returning;
423
  }
424
425
  public function markReturnedAndSave() {
426
    $this->markReturned();
427
    $this->dbSave();
428
  }
429
430
  /**
431
   * Parses extended unit_array which can include not only ships but resources, captains etc
432
   *
433
   * @param $unit_array
434
   */
435
  // TODO - separate shipList and unitList
436
  public function unitsSetFromArray($unit_array) {
437
    foreach($unit_array as $unit_id => $unit_count) {
438
      $unit_count = floatval($unit_count);
439
      if(!$unit_count) {
440
        continue;
441
      }
442
443
      if($this->isShip($unit_id)) {
444
        $this->unitList->unitSetCount($unit_id, $unit_count);
445
      } elseif($this->isResource($unit_id)) {
446
        $this->resource_list[$unit_id] = $unit_count;
447
      } else {
448
        throw new Exception('Trying to pass to fleet non-resource and non-ship ' . var_export($unit_array, true), ERR_ERROR);
449
      }
450
    }
451
  }
452
453
454
  /**
455
   * Sets fleet timers based on flight duration, time on mission (HOLD/EXPLORE) and fleet departure time.
456
   *
457
   * @param int $time_to_travel - flight duration in seconds
458
   * @param int $time_on_mission - time on mission in seconds
459
   * @param int $group_sync_delta_time - delta time to adjust fleet arrival time if fleet is a part of group (i.e. ACS)
460
   * @param int $flight_departure - fleet departure from source planet timestamp. Allows to send fleet in future or in past
461
   */
462
  public function set_times($time_to_travel, $time_on_mission = 0, $group_sync_delta_time = 0, $flight_departure = SN_TIME_NOW) {
463
    $this->_time_launch = $flight_departure;
464
465
    $this->_time_arrive_to_target = $this->_time_launch + $time_to_travel + $group_sync_delta_time;
466
    $this->_time_mission_job_complete = $time_on_mission ? $this->_time_arrive_to_target + $time_on_mission : 0;
467
    $this->_time_return_to_source = ($this->_time_mission_job_complete ? $this->_time_mission_job_complete : $this->_time_arrive_to_target) + $time_to_travel;
468
  }
469
470
471
  public function parse_missile_db_row($missile_db_row) {
472
//    $this->_reset();
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...
473
474
    if(empty($missile_db_row) || !is_array($missile_db_row)) {
475
      return;
476
    }
477
478
//      $planet_start = db_planet_by_vector($irak_original, 'fleet_start_', false, 'name');
0 ignored issues
show
Unused Code Comprehensibility introduced by
61% 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...
479
//      $irak_original['fleet_start_name'] = $planet_start['name'];
480
    $this->missile_target = $missile_db_row['primaer'];
481
482
    $this->_dbId = -$missile_db_row['id'];
483
    $this->_playerOwnerId = $missile_db_row['fleet_owner'];
484
    $this->_mission_type = MT_MISSILE;
485
486
    $this->_target_owner_id = $missile_db_row['fleet_target_owner'];
487
488
    $this->_group_id = 0;
489
    $this->_is_returning = 0;
490
491
    $this->_time_launch = 0; // $irak['start_time'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% 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...
492
    $this->_time_arrive_to_target = 0; // $irak['fleet_start_time'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% 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...
493
    $this->_time_mission_job_complete = 0; // $irak['fleet_end_stay'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% 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...
494
    $this->_time_return_to_source = $missile_db_row['fleet_end_time'];
495
496
    $this->_fleet_start_planet_id = !empty($missile_db_row['fleet_start_planet_id']) ? $missile_db_row['fleet_start_planet_id'] : null;
497
    $this->_fleet_start_galaxy = $missile_db_row['fleet_start_galaxy'];
498
    $this->_fleet_start_system = $missile_db_row['fleet_start_system'];
499
    $this->_fleet_start_planet = $missile_db_row['fleet_start_planet'];
500
    $this->_fleet_start_type = $missile_db_row['fleet_start_type'];
501
502
    $this->_fleet_end_planet_id = !empty($missile_db_row['fleet_end_planet_id']) ? $missile_db_row['fleet_end_planet_id'] : null;
503
    $this->_fleet_end_galaxy = $missile_db_row['fleet_end_galaxy'];
504
    $this->_fleet_end_system = $missile_db_row['fleet_end_system'];
505
    $this->_fleet_end_planet = $missile_db_row['fleet_end_planet'];
506
    $this->_fleet_end_type = $missile_db_row['fleet_end_type'];
507
508
    $this->unitList->unitSetCount(UNIT_DEF_MISSILE_INTERPLANET, $missile_db_row['fleet_amount']);
509
  }
510
511
512
  /**
513
   * @param $from
514
   */
515
  public function set_start_planet($from) {
516
    $this->fleet_start_planet_id = intval($from['id']) ? $from['id'] : null;
517
    $this->fleet_start_galaxy = $from['galaxy'];
518
    $this->fleet_start_system = $from['system'];
519
    $this->fleet_start_planet = $from['planet'];
520
    $this->fleet_start_type = $from['planet_type'];
521
  }
522
523
  /**
524
   * @param $to
525
   */
526
  public function set_end_planet($to) {
527
    $this->target_owner_id = intval($to['id_owner']) ? $to['id_owner'] : 0;
528
    $this->fleet_end_planet_id = intval($to['id']) ? $to['id'] : null;
529
    $this->fleet_end_galaxy = $to['galaxy'];
530
    $this->fleet_end_system = $to['system'];
531
    $this->fleet_end_planet = $to['planet'];
532
    $this->fleet_end_type = $to['planet_type'];
533
  }
534
535
536
537
  // UnitList/Ships access ***************************************************************************************************
538
539
  // TODO - перекрывать пожже - для миссайл-флотов и дефенс-флотов
540
  protected function isShip($unit_id) {
541
    return UnitShip::is_in_group($unit_id);
542
  }
543
544
  /**
545
   * Set unit count of $unit_id to $unit_count
546
   * If there is no $unit_id - it will be created and saved to DB on dbSave
547
   *
548
   * @param int $unit_id
549
   * @param int $unit_count
550
   */
551
  public function shipSetCount($unit_id, $unit_count = 0) {
552
    $this->shipAdjustCount($unit_id, $unit_count, true);
553
  }
554
555
  /**
556
   * Adjust unit count of $unit_id by $unit_count - or just replace value
557
   * If there is no $unit_id - it will be created and saved to DB on dbSave
558
   *
559
   * @param int  $unit_id
560
   * @param int  $unit_count
561
   * @param bool $replace_value
562
   */
563
  public function shipAdjustCount($unit_id, $unit_count = 0, $replace_value = false) {
564
    $this->unitList->unitAdjustCount($unit_id, $unit_count, $replace_value);
565
  }
566
567
  public function shipGetCount($unit_id) {
568
    return $this->unitList->unitGetCount($unit_id);
569
  }
570
571
  public function shipsCountApplyLossMultiplier($ships_lost_multiplier) {
572
    $this->unitList->unitsCountApplyLossMultiplier($ships_lost_multiplier);
573
  }
574
575
  /**
576
   * Returns ship list in fleet
577
   */
578
  public function shipsGetArray() {
579
    return $this->unitList->unitsGetArray();
580
  }
581
582
  public function shipsGetTotal() {
583
    return $this->unitList->unitsCount();
584
  }
585
586
  public function shipsGetCapacity() {
587
    return $this->unitList->unitsCapacity();
588
  }
589
590
  public function shipsGetHoldFree() {
591
    return max(0, $this->shipsGetCapacity() - $this->resourcesGetTotal());
592
  }
593
594
  public function shipsGetTotalById($ship_id) {
595
    return $this->unitList->unitsCountById($ship_id);
596
  }
597
598
  /**
599
   * Возвращает ёмкость переработчиков во флоте
600
   *
601
   * @param array $recycler_info
602
   *
603
   * @return int
604
   *
605
   * @version 41a6.31
606
   */
607
  public function shipsGetCapacityRecyclers(array $recycler_info) {
608
    $recyclers_incoming_capacity = 0;
609
    $fleet_data = $this->shipsGetArray();
610
    foreach($recycler_info as $recycler_id => $recycler_data) {
611
      $recyclers_incoming_capacity += $fleet_data[$recycler_id] * $recycler_data['capacity'];
612
    }
613
614
    return $recyclers_incoming_capacity;
615
  }
616
617
  /**
618
   * Restores fleet or resources to planet
619
   *
620
   * @param bool $start
621
   * @param int  $result
622
   *
623
   * @return int
624
   */
625
  // TODO - split to functions
626
  public function shipsLand($start = true, &$result = CACHE_NOTHING) {
627
    sn_db_transaction_check(true);
628
629
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
630
    if($this->isEmpty()) {
631
      return $result;
632
    }
633
634
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
635
636
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
637
    // TODO Проверить от многократного срабатывания !!!
638
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
639
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
640
641
    // Узнаем ИД владельца планеты.
642
    // С блокировкой, поскольку эта функция может быть вызвана только из менеджера летящих флотов.
643
    // А там уже всё заблокировано как надо и повторная блокировка не вызовет дедлок.
644
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
645
    // Блокируем пользователя
646
    // TODO - вообще-то нам уже известен пользователь в МЛФ - так что можно просто передать его сюда
647
    $user = db_user_by_id($planet_arrival['id_owner'], true);
648
649
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
650
    // Флот, который возвращается на захваченную планету, пропадает
651
    // Ship landing is possible only to fleet owner's planet
652
    if($this->getPlayerOwnerId() == $planet_arrival['id_owner']) {
653
      $db_changeset = array();
654
655
      $fleet_array = $this->shipsGetArray();
656
      foreach($fleet_array as $ship_id => $ship_count) {
657
        if($ship_count) {
658
          $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $planet_arrival['id']);
659
        }
660
      }
661
662
      // Adjusting ship amount on planet
663
      if(!empty($db_changeset)) {
664
        db_changeset_apply($db_changeset);
665
      }
666
667
      // Restoring resources to planet
668
      $this->resourcesUnload($start, $result);
669
    }
670
671
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
672
673
    $result = RestoreFleetToPlanet($this, $start, $result);
674
675
    $this->dbDelete();
676
677
    return $result;
678
  }
679
680
681
  // Resources access ***************************************************************************************************
682
683
  /**
684
   * Extracts resources value from db_row
685
   *
686
   * @param array $db_row
687
   *
688
   * @internal param Fleet $that
689
   * @version 41a6.31
690
   */
691
  protected function resourcesExtract(array &$db_row) {
692
    $this->resource_list = array(
693
      RES_METAL     => !empty($db_row['fleet_resource_metal']) ? floor($db_row['fleet_resource_metal']) : 0,
694
      RES_CRYSTAL   => !empty($db_row['fleet_resource_crystal']) ? floor($db_row['fleet_resource_crystal']) : 0,
695
      RES_DEUTERIUM => !empty($db_row['fleet_resource_deuterium']) ? floor($db_row['fleet_resource_deuterium']) : 0,
696
    );
697
  }
698
699
  protected function resourcesInject(array &$db_row) {
700
    $db_row['fleet_resource_metal'] = $this->resource_list[RES_METAL];
701
    $db_row['fleet_resource_crystal'] = $this->resource_list[RES_CRYSTAL];
702
    $db_row['fleet_resource_deuterium'] = $this->resource_list[RES_DEUTERIUM];
703
  }
704
705
  /**
706
   * Set current resource list from array of units
707
   *
708
   * @param array $resource_list
709
   */
710
  public function resourcesSet($resource_list) {
711
    if(!empty($this->propertiesAdjusted['resource_list'])) {
712
      throw new PropertyAccessException('Property "resource_list" already was adjusted so no SET is possible until dbSave in ' . get_called_class() . '::unitSetResourceList', ERR_ERROR);
713
    }
714
    $this->resourcesAdjust($resource_list, true);
715
  }
716
717
  /**
718
   * Updates fleet resource list with deltas
719
   *
720
   * @param $resource_delta_list
721
   */
722
  public function resourcesAdjust($resource_delta_list, $replace_value = false) {
723
    !is_array($resource_delta_list) ? $resource_delta_list = array() : false;
724
725
    foreach($resource_delta_list as $resource_id => $unit_delta) {
726
      if(!UnitResourceLoot::is_in_group($resource_id) || !($unit_delta = floor($unit_delta))) {
727
        // Not a resource or no resources - continuing
728
        continue;
729
      }
730
731
      if($replace_value) {
732
        $this->resource_list[$resource_id] = $unit_delta;
733
      } else {
734
        $this->resource_list[$resource_id] += $unit_delta;
735
        // Preparing changes
736
        $this->resource_delta[$resource_id] += $unit_delta;
737
        $this->propertiesAdjusted['resource_list'] = 1;
738
      }
739
740
      // Check for negative unit value
741
      if($this->resource_list[$resource_id] < 0) {
742
        // TODO
743
        throw new Exception('Resource ' . $resource_id . ' will become negative in ' . get_called_class() . '::unitAdjustResourceList', ERR_ERROR);
744
      }
745
    }
746
  }
747
748
  public function resourcesGetTotal() {
749
    return empty($this->resource_list) || !is_array($this->resource_list) ? 0 : array_sum($this->resource_list);
750
  }
751
752
  /**
753
   * @param array $rate
754
   *
755
   * @return float
756
   */
757
  public function resourcesGetTotalInMetal(array $rate) {
758
    return
759
      $this->resource_list[RES_METAL] * $rate[RES_METAL]
760
      + $this->resource_list[RES_CRYSTAL] * $rate[RES_CRYSTAL] / $rate[RES_METAL]
761
      + $this->resource_list[RES_DEUTERIUM] * $rate[RES_DEUTERIUM] / $rate[RES_METAL];
762
  }
763
764
  /**
765
   * Returns resource list in fleet
766
   */
767
  // TODO
768
  public function resourcesGetList() {
769
    return $this->resource_list;
770
  }
771
772
  public function resourcesReset() {
773
    $this->resourcesSet(array(
774
      RES_METAL     => 0,
775
      RES_CRYSTAL   => 0,
776
      RES_DEUTERIUM => 0,
777
    ));
778
  }
779
780
  /**
781
   * Restores fleet or resources to planet
782
   *
783
   * @param bool $start
784
   * @param bool $only_resources
0 ignored issues
show
Bug introduced by
There is no parameter named $only_resources. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
785
   * @param int  $result
786
   *
787
   * @return int
788
   */
789
  public function resourcesUnload($start = true, &$result = CACHE_NOTHING) {
790
    sn_db_transaction_check(true);
791
792
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
793
    if(!$this->resourcesGetTotal()) {
794
      return $result;
795
    }
796
797
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
798
799
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
800
    // TODO Проверить от многократного срабатывания !!!
801
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
802
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
803
804
805
    // Узнаем ИД владельца планеты.
806
    // С блокировкой, поскольку эта функция может быть вызвана только из менеджера летящих флотов.
807
    // А там уже всё заблокировано как надо и повторная блокировка не вызовет дедлок.
808
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
809
810
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
811
812
    // Restoring resources to planet
813
    if($this->resourcesGetTotal()) {
814
      $fleet_resources = $this->resourcesGetList();
815
      db_planet_set_by_id($planet_arrival['id'],
816
        "`metal` = `metal` + '{$fleet_resources[RES_METAL]}', `crystal` = `crystal` + '{$fleet_resources[RES_CRYSTAL]}', `deuterium` = `deuterium` + '{$fleet_resources[RES_DEUTERIUM]}'");
817
    }
818
819
    $this->resourcesReset();
820
    $this->markReturned();
821
822
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
823
824
    return $result;
825
  }
826
827
828
  protected function isResource($unit_id) {
829
    return UnitResourceLoot::is_in_group($unit_id);
830
  }
831
832
}
833