Completed
Push — work-fleets ( abbbcf...8b8b7f )
by SuperNova.WS
05:13
created

Fleet::make_db_insert_set()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 36
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
c 8
b 0
f 0
dl 0
loc 36
rs 8.439
cc 5
eloc 26
nc 16
nop 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A Fleet::shipsGetHoldFree() 0 3 1
A Fleet::shipsGetTotalById() 0 3 1
A Fleet::shipsGetCapacityRecyclers() 0 9 2
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
    // TODO: Implement isEmpty() method.
274
    return false;
275
  }
276
277
//  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...
278
//    return $this->playerOwnerId;
279
//  }
280
281
  /**
282
   * Initializes Fleet from user params and posts it to DB
283
   */
284
  public function dbInsert() {
285
    // WARNING! MISSION TIMES MUST BE SET WITH set_times() method!
286
    // TODO - more checks!
287
    if(empty($this->_time_launch)) {
288
      die('Fleet time not set!');
289
    }
290
291
    parent::dbInsert();
292
  }
293
294
295
  /* FLEET DB ACCESS =================================================================================================*/
296
297
  /**
298
   * LOCK - Lock all records which can be used with mission
299
   *
300
   * @param $mission_data
301
   * @param $fleet_id
302
   *
303
   * @return array|bool|mysqli_result|null
304
   */
305
  public function dbLockFlying(&$mission_data) {
306
    // Тупо лочим всех юзеров, чьи флоты летят или улетают с координат отбытия/прибытия $fleet_row
307
    // Что бы делать это умно - надо учитывать fleet__mess во $fleet_row и в таблице fleets
308
309
    $fleet_id_safe = idval($this->_dbId);
310
311
    return doquery(
312
    // Блокировка самого флота
313
      "SELECT 1 FROM {{fleets}} AS f " .
314
315
      // Блокировка всех юнитов, принадлежащих этому флоту
316
      "LEFT JOIN {{unit}} as unit ON unit.unit_location_type = " . static::$locationType . " AND unit.unit_location_id = f.fleet_id " .
317
318
      // Блокировка всех прилетающих и улетающих флотов, если нужно
319
      // TODO - lock fleets by COORDINATES
320
      ($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 " : '') .
321
      // Блокировка всех юнитов, принадлежащих прилетающим и улетающим флотам - ufd = unit_fleet_destination
322
      ($mission_data['dst_fleets'] ? "LEFT JOIN {{unit}} AS ufd ON ufd.unit_location_type = " . static::$locationType . " AND ufd.unit_location_id = fd.fleet_id " : '') .
323
324
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{users}} AS ud ON ud.id = f.fleet_target_owner " : '') .
325
      // Блокировка всех юнитов, принадлежащих владельцу планеты-цели
326
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS unit_player_dest ON unit_player_dest.unit_player_id = ud.id " : '') .
327
      // Блокировка планеты-цели
328
      ($mission_data['dst_planet'] ? "LEFT JOIN {{planets}} AS pd ON pd.id = f.fleet_end_planet_id " : '') .
329
      // Блокировка всех юнитов, принадлежащих планете-цели - НЕ НУЖНО. Уже залочили ранее, как принадлежащие игроку-цели
330
//      ($mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS upd ON upd.unit_location_type = " . LOC_PLANET . " AND upd.unit_location_id = pd.id " : '') .
331
332
333
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{users}} AS us ON us.id = f.fleet_owner " : '') .
334
      // Блокировка всех юнитов, принадлежащих владельцу флота
335
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS unit_player_src ON unit_player_src.unit_player_id = us.id " : '') .
336
      // Блокировка планеты отправления
337
      ($mission_data['src_planet'] ? "LEFT JOIN {{planets}} AS ps ON ps.id = f.fleet_start_planet_id " : '') .
338
      // Блокировка всех юнитов, принадлежащих планете с которой юниты были отправлены - НЕ НУЖНО. Уже залочили ранее, как принадлежащие владельцу флота
339
//      ($mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS ups ON ups.unit_location_type = " . LOC_PLANET . " AND ups.unit_location_id = ps.id " : '') .
340
341
      "WHERE f.fleet_id = {$fleet_id_safe} GROUP BY 1 FOR UPDATE"
342
    );
343
  }
344
345
346
  /* FLEET HELPERS =====================================================================================================*/
347
  /**
348
   * Forcibly returns fleet before time outs
349
   */
350
  public function commandReturn() {
351
    $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;
352
353
    $this->markReturned();
354
355
    // Считаем, что флот уже долетел TODO
356
    $this->time_arrive_to_target = SN_TIME_NOW;
357
    // Убираем флот из группы
358
    $this->group_id = 0;
359
    // Отменяем работу в точке назначения
360
    $this->time_mission_job_complete = 0;
361
    // TODO - правильно вычслять время возвращения - по проделанному пути, а не по старому времени возвращения
362
    $this->time_return_to_source = $ReturnFlyingTime;
363
364
    // Записываем изменения в БД
365
    $this->dbSave();
366
367
    if($this->_group_id) {
368
      // TODO: Make here to delete only one AKS - by adding aks_fleet_count to AKS table
369
      db_fleet_aks_purge();
370
    }
371
  }
372
373
374
375
376
377
  /**
378
   * @return array
379
   */
380
  public function target_coordinates_without_type() {
381
    return array(
382
      'galaxy' => $this->_fleet_end_galaxy,
383
      'system' => $this->_fleet_end_system,
384
      'planet' => $this->_fleet_end_planet,
385
    );
386
  }
387
388
  /**
389
   * @return array
390
   */
391
  public function target_coordinates_typed() {
392
    return array(
393
      'galaxy' => $this->_fleet_end_galaxy,
394
      'system' => $this->_fleet_end_system,
395
      'planet' => $this->_fleet_end_planet,
396
      'type'   => $this->_fleet_end_type,
397
    );
398
  }
399
400
  /**
401
   * @return array
402
   */
403
  public function launch_coordinates_typed() {
404
    return array(
405
      'galaxy' => $this->_fleet_start_galaxy,
406
      'system' => $this->_fleet_start_system,
407
      'planet' => $this->_fleet_start_planet,
408
      'type'   => $this->_fleet_start_type,
409
    );
410
  }
411
412
413
  /**
414
   * Restores fleet or resources to planet
415
   *
416
   * @param bool $start
417
   * @param bool $only_resources
418
   * @param int  $result
419
   *
420
   * @return int
421
   */
422
  // TODO - split to functions
423
  public function RestoreFleetToPlanet($start = true, $only_resources = false, &$result = CACHE_NOTHING) {
424
    sn_db_transaction_check(true);
425
426
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
427
    if($this->isEmpty() || ($this->_is_returning == 1 && $only_resources)) {
428
      return $result;
429
    }
430
431
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
432
433
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
434
    // TODO Проверить от многократного срабатывания !!!
435
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
436
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
437
    // Узнаем ИД владельца планеты - без блокировки
438
    $planet_arrival = db_planet_by_vector($coordinates, '', false, 'id_owner');
439
    // Блокируем пользователя
440
    $user = db_user_by_id($planet_arrival['id_owner'], true);
441
    // Блокируем планету
442
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
443
    // Блокируем флот
444
445
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
446
    // Флот, который возвращается на захваченную планету, пропадает
447
    if($start && $this->_is_returning == 1 && $planet_arrival['id_owner'] != $this->_playerOwnerId) {
448
      $result = RestoreFleetToPlanet($this, $start, $only_resources, $result);
449
450
      $this->dbDelete();
451
452
      return $result;
453
    }
454
455
    if(!$only_resources) {
456
      // Landing ships
457
      $db_changeset = array();
458
459
      if($this->_playerOwnerId == $planet_arrival['id_owner']) {
460
        $fleet_array = $this->shipsGetArray();
461
        foreach($fleet_array as $ship_id => $ship_count) {
462
          if($ship_count) {
463
            $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $planet_arrival['id']);
464
          }
465
        }
466
467
        // Adjusting ship amount on planet
468
        if(!empty($db_changeset)) {
469
          db_changeset_apply($db_changeset);
470
        }
471
      }
472
    } else {
473
      $this->resourcesReset();
474
      $this->markReturned();
475
      $this->dbSave();
476
    }
477
478
    // Restoring resources to planet
479
    if($this->resourcesGetTotal() != 0) {
480
      $fleet_resources = $this->resourcesGetList();
481
      db_planet_set_by_id($planet_arrival['id'],
482
        "`metal` = `metal` + '{$fleet_resources[RES_METAL]}', `crystal` = `crystal` + '{$fleet_resources[RES_CRYSTAL]}', `deuterium` = `deuterium` + '{$fleet_resources[RES_DEUTERIUM]}'");
483
    }
484
485
    if(!$only_resources) {
486
      $this->dbDelete();
487
    }
488
489
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
490
491
    return RestoreFleetToPlanet($this, $start, $only_resources, $result);
492
  }
493
494
495
  /**
496
   * Sets object fields for fleet return
497
   */
498
  public function markReturned() {
499
    // TODO - Проверка - а не возвращается ли уже флот?
500
    $this->is_returning = 1;
501
  }
502
503
  public function isReturning() {
504
    return 1 == $this->_is_returning;
505
  }
506
507
  public function markReturnedAndSave() {
508
    $this->markReturned();
509
    $this->dbSave();
510
  }
511
512
  /**
513
   * Parses extended unit_array which can include not only ships but resources, captains etc
514
   *
515
   * @param $unit_array
516
   */
517
  // TODO - separate shipList and unitList
518
  public function unitsSetFromArray($unit_array) {
519
    foreach($unit_array as $unit_id => $unit_count) {
520
      $unit_count = floatval($unit_count);
521
      if(!$unit_count) {
522
        continue;
523
      }
524
525
      if($this->isShip($unit_id)) {
526
        $this->unitList->unitSetCount($unit_id, $unit_count);
527
      } elseif($this->isResource($unit_id)) {
528
        $this->resource_list[$unit_id] = $unit_count;
529
      } else {
530
        throw new Exception('Trying to pass to fleet non-resource and non-ship ' . var_export($unit_array, true), ERR_ERROR);
531
      }
532
    }
533
  }
534
535
536
  /**
537
   * Sets fleet timers based on flight duration, time on mission (HOLD/EXPLORE) and fleet departure time.
538
   *
539
   * @param int $time_to_travel - flight duration in seconds
540
   * @param int $time_on_mission - time on mission in seconds
541
   * @param int $group_sync_delta_time - delta time to adjust fleet arrival time if fleet is a part of group (i.e. ACS)
542
   * @param int $flight_departure - fleet departure from source planet timestamp. Allows to send fleet in future or in past
543
   */
544
  public function set_times($time_to_travel, $time_on_mission = 0, $group_sync_delta_time = 0, $flight_departure = SN_TIME_NOW) {
545
    $this->_time_launch = $flight_departure;
546
547
    $this->_time_arrive_to_target = $this->_time_launch + $time_to_travel + $group_sync_delta_time;
548
    $this->_time_mission_job_complete = $time_on_mission ? $this->_time_arrive_to_target + $time_on_mission : 0;
549
    $this->_time_return_to_source = ($this->_time_mission_job_complete ? $this->_time_mission_job_complete : $this->_time_arrive_to_target) + $time_to_travel;
550
  }
551
552
553
  public function parse_missile_db_row($missile_db_row) {
554
//    $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...
555
556
    if(empty($missile_db_row) || !is_array($missile_db_row)) {
557
      return;
558
    }
559
560
//      $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...
561
//      $irak_original['fleet_start_name'] = $planet_start['name'];
562
    $this->missile_target = $missile_db_row['primaer'];
563
564
    $this->_dbId = -$missile_db_row['id'];
565
    $this->_playerOwnerId = $missile_db_row['fleet_owner'];
566
    $this->_mission_type = MT_MISSILE;
567
568
    $this->_target_owner_id = $missile_db_row['fleet_target_owner'];
569
570
    $this->_group_id = 0;
571
    $this->_is_returning = 0;
572
573
    $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...
574
    $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...
575
    $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...
576
    $this->_time_return_to_source = $missile_db_row['fleet_end_time'];
577
578
    $this->_fleet_start_planet_id = !empty($missile_db_row['fleet_start_planet_id']) ? $missile_db_row['fleet_start_planet_id'] : null;
579
    $this->_fleet_start_galaxy = $missile_db_row['fleet_start_galaxy'];
580
    $this->_fleet_start_system = $missile_db_row['fleet_start_system'];
581
    $this->_fleet_start_planet = $missile_db_row['fleet_start_planet'];
582
    $this->_fleet_start_type = $missile_db_row['fleet_start_type'];
583
584
    $this->_fleet_end_planet_id = !empty($missile_db_row['fleet_end_planet_id']) ? $missile_db_row['fleet_end_planet_id'] : null;
585
    $this->_fleet_end_galaxy = $missile_db_row['fleet_end_galaxy'];
586
    $this->_fleet_end_system = $missile_db_row['fleet_end_system'];
587
    $this->_fleet_end_planet = $missile_db_row['fleet_end_planet'];
588
    $this->_fleet_end_type = $missile_db_row['fleet_end_type'];
589
590
    $this->unitList->unitSetCount(UNIT_DEF_MISSILE_INTERPLANET, $missile_db_row['fleet_amount']);
591
  }
592
593
594
  /**
595
   * @param $from
596
   */
597
  public function set_start_planet($from) {
598
    $this->fleet_start_planet_id = intval($from['id']) ? $from['id'] : null;
599
    $this->fleet_start_galaxy = $from['galaxy'];
600
    $this->fleet_start_system = $from['system'];
601
    $this->fleet_start_planet = $from['planet'];
602
    $this->fleet_start_type = $from['planet_type'];
603
  }
604
605
  /**
606
   * @param $to
607
   */
608
  public function set_end_planet($to) {
609
    $this->target_owner_id = intval($to['id_owner']) ? $to['id_owner'] : 0;
610
    $this->fleet_end_planet_id = intval($to['id']) ? $to['id'] : null;
611
    $this->fleet_end_galaxy = $to['galaxy'];
612
    $this->fleet_end_system = $to['system'];
613
    $this->fleet_end_planet = $to['planet'];
614
    $this->fleet_end_type = $to['planet_type'];
615
  }
616
617
618
619
  // UnitList/Ships access ***************************************************************************************************
620
621
  // TODO - перекрывать пожже - для миссайл-флотов и дефенс-флотов
622
  protected function isShip($unit_id) {
623
    return UnitShip::is_in_group($unit_id);
624
  }
625
626
  /**
627
   * Set unit count of $unit_id to $unit_count
628
   * If there is no $unit_id - it will be created and saved to DB on dbSave
629
   *
630
   * @param int $unit_id
631
   * @param int $unit_count
632
   */
633
  public function shipSetCount($unit_id, $unit_count = 0) {
634
    $this->shipAdjustCount($unit_id, $unit_count, true);
635
  }
636
637
  /**
638
   * Adjust unit count of $unit_id by $unit_count - or just replace value
639
   * If there is no $unit_id - it will be created and saved to DB on dbSave
640
   *
641
   * @param int  $unit_id
642
   * @param int  $unit_count
643
   * @param bool $replace_value
644
   */
645
  public function shipAdjustCount($unit_id, $unit_count = 0, $replace_value = false) {
646
    $this->unitList->unitAdjustCount($unit_id, $unit_count, $replace_value);
647
  }
648
649
  public function shipGetCount($unit_id) {
650
    return $this->unitList->unitGetCount($unit_id);
651
  }
652
653
  public function shipsCountApplyLossMultiplier($ships_lost_multiplier) {
654
    $this->unitList->unitsCountApplyLossMultiplier($ships_lost_multiplier);
655
  }
656
657
  /**
658
   * Returns ship list in fleet
659
   */
660
  public function shipsGetArray() {
661
    return $this->unitList->unitsGetArray();
662
  }
663
664
  public function shipsGetTotal() {
665
    return $this->unitList->unitsCount();
666
  }
667
668
  public function shipsGetCapacity() {
669
    return $this->unitList->unitsCapacity();
670
  }
671
672
  public function shipsGetHoldFree() {
673
    return max(0, $this->shipsGetCapacity() - $this->resourcesGetTotal());
674
  }
675
676
  public function shipsGetTotalById($ship_id) {
677
    return $this->unitList->unitsCountById($ship_id);
678
  }
679
680
  /**
681
   * Возвращает ёмкость переработчиков во флоте
682
   *
683
   * @param array $recycler_info
684
   *
685
   * @return int
686
   *
687
   * @version 41a6.30
688
   */
689
  public function shipsGetCapacityRecyclers(array $recycler_info) {
690
    $recyclers_incoming_capacity = 0;
691
    $fleet_data = $this->shipsGetArray();
692
    foreach($recycler_info as $recycler_id => $recycler_data) {
693
      $recyclers_incoming_capacity += $fleet_data[$recycler_id] * $recycler_data['capacity'];
694
    }
695
696
    return $recyclers_incoming_capacity;
697
  }
698
699
  // Resources access ***************************************************************************************************
700
701
  /**
702
   * Extracts resources value from db_row
703
   *
704
   * @param array $db_row
705
   *
706
   * @internal param Fleet $that
707
   * @version 41a6.30
708
   */
709
  protected function resourcesExtract(array &$db_row) {
710
    $this->resource_list = array(
711
      RES_METAL     => !empty($db_row['fleet_resource_metal']) ? floor($db_row['fleet_resource_metal']) : 0,
712
      RES_CRYSTAL   => !empty($db_row['fleet_resource_crystal']) ? floor($db_row['fleet_resource_crystal']) : 0,
713
      RES_DEUTERIUM => !empty($db_row['fleet_resource_deuterium']) ? floor($db_row['fleet_resource_deuterium']) : 0,
714
    );
715
  }
716
717
  protected function resourcesInject(array &$db_row) {
718
    $db_row['fleet_resource_metal'] = $this->resource_list[RES_METAL];
719
    $db_row['fleet_resource_crystal'] = $this->resource_list[RES_CRYSTAL];
720
    $db_row['fleet_resource_deuterium'] = $this->resource_list[RES_DEUTERIUM];
721
  }
722
723
  /**
724
   * Set current resource list from array of units
725
   *
726
   * @param array $resource_list
727
   */
728
  public function resourcesSet($resource_list) {
729
    if(!empty($this->propertiesAdjusted['resource_list'])) {
730
      throw new PropertyAccessException('Property "resource_list" already was adjusted so no SET is possible until dbSave in ' . get_called_class() . '::unitSetResourceList', ERR_ERROR);
731
    }
732
    $this->resourcesAdjust($resource_list, true);
733
  }
734
735
  /**
736
   * Updates fleet resource list with deltas
737
   *
738
   * @param $resource_delta_list
739
   */
740
  public function resourcesAdjust($resource_delta_list, $replace_value = false) {
741
    !is_array($resource_delta_list) ? $resource_delta_list = array() : false;
742
743
    foreach($resource_delta_list as $resource_id => $unit_delta) {
744
      if(!UnitResourceLoot::is_in_group($resource_id) || !($unit_delta = floor($unit_delta))) {
745
        // Not a resource or no resources - continuing
746
        continue;
747
      }
748
749
      if($replace_value) {
750
        $this->resource_list[$resource_id] = $unit_delta;
751
      } else {
752
        $this->resource_list[$resource_id] += $unit_delta;
753
        // Preparing changes
754
        $this->resource_delta[$resource_id] += $unit_delta;
755
      }
756
757
      // Check for negative unit value
758
      if($this->resource_list[$resource_id] < 0) {
759
        // TODO
760
        throw new Exception('Resource ' . $resource_id . ' will become negative in ' . get_called_class() . '::unitAdjustResourceList', ERR_ERROR);
761
      }
762
    }
763
764
    $this->propertiesAdjusted['resource_list'] = 1;
765
766
  }
767
768
  public function resourcesGetTotal() {
769
    return empty($this->resource_list) || !is_array($this->resource_list) ? 0 : array_sum($this->resource_list);
770
  }
771
772
  /**
773
   * @param array $rate
774
   *
775
   * @return float
776
   */
777
  public function resourcesGetTotalInMetal(array $rate) {
778
    return
779
      $this->resource_list[RES_METAL] * $rate[RES_METAL]
780
      + $this->resource_list[RES_CRYSTAL] * $rate[RES_CRYSTAL] / $rate[RES_METAL]
781
      + $this->resource_list[RES_DEUTERIUM] * $rate[RES_DEUTERIUM] / $rate[RES_METAL];
782
  }
783
784
  /**
785
   * Returns resource list in fleet
786
   */
787
  // TODO
788
  public function resourcesGetList() {
789
    return $this->resource_list;
790
  }
791
792
  public function resourcesReset() {
793
    $this->resourcesSet(array(
794
      RES_METAL     => 0,
795
      RES_CRYSTAL   => 0,
796
      RES_DEUTERIUM => 0,
797
    ));
798
  }
799
800
  protected function isResource($unit_id) {
801
    return UnitResourceLoot::is_in_group($unit_id);
802
  }
803
804
}
805