Completed
Push — work-fleets ( 23812c...abbbcf )
by SuperNova.WS
05:51
created

Fleet::dbInsert()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 4
nc 2
nop 0
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   => 'extractResources',
140
      P_METHOD_INJECT    => 'injectResources',
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
  /* FLEET DB ACCESS =================================================================================================*/
283
284
  /**
285
   * LOCK - Lock all records which can be used with mission
286
   *
287
   * @param $mission_data
288
   * @param $fleet_id
289
   *
290
   * @return array|bool|mysqli_result|null
291
   */
292
  public function db_fleet_lock_flying(&$mission_data) {
293
    // Тупо лочим всех юзеров, чьи флоты летят или улетают с координат отбытия/прибытия $fleet_row
294
    // Что бы делать это умно - надо учитывать fleet__mess во $fleet_row и в таблице fleets
295
296
    $fleet_id_safe = idval($this->_dbId);
297
298
    return doquery(
299
    // Блокировка самого флота
300
      "SELECT 1 FROM {{fleets}} AS f " .
301
302
      // Блокировка всех юнитов, принадлежащих этому флоту
303
      "LEFT JOIN {{unit}} as unit ON unit.unit_location_type = " . static::$locationType . " AND unit.unit_location_id = f.fleet_id " .
304
305
      // Блокировка всех прилетающих и улетающих флотов, если нужно
306
      // TODO - lock fleets by COORDINATES
307
      ($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 " : '') .
308
      // Блокировка всех юнитов, принадлежащих прилетающим и улетающим флотам - ufd = unit_fleet_destination
309
      ($mission_data['dst_fleets'] ? "LEFT JOIN {{unit}} AS ufd ON ufd.unit_location_type = " . static::$locationType . " AND ufd.unit_location_id = fd.fleet_id " : '') .
310
311
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{users}} AS ud ON ud.id = f.fleet_target_owner " : '') .
312
      // Блокировка всех юнитов, принадлежащих владельцу планеты-цели
313
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS unit_player_dest ON unit_player_dest.unit_player_id = ud.id " : '') .
314
      // Блокировка планеты-цели
315
      ($mission_data['dst_planet'] ? "LEFT JOIN {{planets}} AS pd ON pd.id = f.fleet_end_planet_id " : '') .
316
      // Блокировка всех юнитов, принадлежащих планете-цели - НЕ НУЖНО. Уже залочили ранее, как принадлежащие игроку-цели
317
//      ($mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS upd ON upd.unit_location_type = " . LOC_PLANET . " AND upd.unit_location_id = pd.id " : '') .
318
319
320
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{users}} AS us ON us.id = f.fleet_owner " : '') .
321
      // Блокировка всех юнитов, принадлежащих владельцу флота
322
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS unit_player_src ON unit_player_src.unit_player_id = us.id " : '') .
323
      // Блокировка планеты отправления
324
      ($mission_data['src_planet'] ? "LEFT JOIN {{planets}} AS ps ON ps.id = f.fleet_start_planet_id " : '') .
325
      // Блокировка всех юнитов, принадлежащих планете с которой юниты были отправлены - НЕ НУЖНО. Уже залочили ранее, как принадлежащие владельцу флота
326
//      ($mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS ups ON ups.unit_location_type = " . LOC_PLANET . " AND ups.unit_location_id = ps.id " : '') .
327
328
      "WHERE f.fleet_id = {$fleet_id_safe} GROUP BY 1 FOR UPDATE"
329
    );
330
  }
331
332
  /**
333
   * DELETE - Удаляет текущий флот из базы
334
   *
335
   * @return array|bool|mysqli_result|null
336
   */
337
  public function db_delete_this_fleet() {
338
    $fleet_id_safe = idval($this->_dbId);
339
    if(!empty($fleet_id_safe)) {
340
      $result = doquery("DELETE FROM {{fleets}} WHERE `fleet_id` = {$fleet_id_safe} LIMIT 1;");
341
    } else {
342
      $result = false;
343
    }
344
345
    db_unit_list_delete(0, static::$locationType, $this->_dbId, 0);
346
347
//    $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...
348
349
    return $result;
350
  }
351
352
353
354
355
356
357
358
359
360
361
  /* FLEET HELPERS =====================================================================================================*/
362
  /**
363
   * Forcibly returns fleet before time outs
364
   */
365
  public function commandReturn() {
366
    $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;
367
368
    $this->mark_fleet_as_returned();
369
370
    // Считаем, что флот уже долетел TODO
371
    $this->time_arrive_to_target = SN_TIME_NOW;
372
    // Убираем флот из группы
373
    $this->group_id = 0;
374
    // Отменяем работу в точке назначения
375
    $this->time_mission_job_complete = 0;
376
    // TODO - правильно вычслять время возвращения - по проделанному пути, а не по старому времени возвращения
377
    $this->time_return_to_source = $ReturnFlyingTime;
378
379
    // Записываем изменения в БД
380
    $this->dbSave();
381
382
    if($this->_group_id) {
383
      // TODO: Make here to delete only one AKS - by adding aks_fleet_count to AKS table
384
      db_fleet_aks_purge();
385
    }
386
  }
387
388
  /**
389
   * Sets object fields for fleet return
390
   */
391
  public function mark_fleet_as_returned() {
392
    // TODO - Проверка - а не возвращается ли уже флот?
393
    $this->is_returning = 1;
394
  }
395
396
397
  /**
398
   * @return array
399
   */
400
  public function target_coordinates_without_type() {
401
    return array(
402
      'galaxy' => $this->_fleet_end_galaxy,
403
      'system' => $this->_fleet_end_system,
404
      'planet' => $this->_fleet_end_planet,
405
    );
406
  }
407
408
  /**
409
   * @return array
410
   */
411
  public function target_coordinates_typed() {
412
    return array(
413
      'galaxy' => $this->_fleet_end_galaxy,
414
      'system' => $this->_fleet_end_system,
415
      'planet' => $this->_fleet_end_planet,
416
      'type'   => $this->_fleet_end_type,
417
    );
418
  }
419
420
  /**
421
   * @return array
422
   */
423
  public function launch_coordinates_typed() {
424
    return array(
425
      'galaxy' => $this->_fleet_start_galaxy,
426
      'system' => $this->_fleet_start_system,
427
      'planet' => $this->_fleet_start_planet,
428
      'type'   => $this->_fleet_start_type,
429
    );
430
  }
431
432
433
  /**
434
   * Restores fleet or resources to planet
435
   *
436
   * @param      $fleet_row
437
   * @param bool $start
438
   * @param bool $only_resources
439
   * @param bool $safe_fleet
440
   * @param      $result
441
   *
442
   * @return int
443
   */
444
  // TODO - split to functions
445
  public function RestoreFleetToPlanet($start = true, $only_resources = false, $safe_fleet = false, &$result = CACHE_NOTHING) {
0 ignored issues
show
Unused Code introduced by
The parameter $safe_fleet is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
446
    sn_db_transaction_check(true);
447
448
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
449
    if(!$this->_dbId || ($this->_is_returning == 1 && $only_resources)) {
450
      return $result;
451
    }
452
453
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
454
455
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
456
    // TODO Проверить от многократного срабатывания !!!
457
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
458
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
459
    // Узнаем ИД владельца планеты - без блокировки
460
    $planet_arrival = db_planet_by_vector($coordinates, '', false, 'id_owner');
461
    // Блокируем пользователя
462
    $user = db_user_by_id($planet_arrival['id_owner'], true);
463
    // Блокируем планету
464
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
465
    // Блокируем флот
466
467
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
468
    // Флот, который возвращается на захваченную планету, пропадает
469
    if($start && $this->_is_returning == 1 && $planet_arrival['id_owner'] != $this->_playerOwnerId) {
470
      $result = RestoreFleetToPlanet($this, $start, $only_resources, $result);
471
472
      $this->db_delete_this_fleet();
473
474
      return $result;
475
    }
476
477
//pdump($planet_arrival);
478
    if(!$only_resources) {
479
      // Landing ships
480
      $db_changeset = array();
481
482
      if($this->_playerOwnerId == $planet_arrival['id_owner']) {
483
        $fleet_array = $this->get_unit_list();
484
        foreach($fleet_array as $ship_id => $ship_count) {
485
          if($ship_count) {
486
            $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $planet_arrival['id']);
487
          }
488
        }
489
490
        // Adjusting ship amount on planet
491
        if(!empty($db_changeset)) {
492
          db_changeset_apply($db_changeset);
493
        }
494
      }
495
    } else {
496
      $this->set_zero_cargo();
497
      $this->mark_fleet_as_returned();
498
      $this->dbSave();
499
    }
500
501
    // Restoring resources to planet
502
    if($this->get_resources_amount() != 0) {
503
      $fleet_resources = $this->get_resource_list();
504
      db_planet_set_by_id($planet_arrival['id'],
505
        "`metal` = `metal` + '{$fleet_resources[RES_METAL]}', `crystal` = `crystal` + '{$fleet_resources[RES_CRYSTAL]}', `deuterium` = `deuterium` + '{$fleet_resources[RES_DEUTERIUM]}'");
506
    }
507
508
    if(!$only_resources) {
509
      $this->db_delete_this_fleet();
510
    }
511
512
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
513
514
    return RestoreFleetToPlanet($this, $start, $only_resources, $result);
515
  }
516
517
518
519
520
521
522
523
524
525
526
527
  /**
528
   * @param $acs_id
529
   * @param $mission_id - currently only MT_AKS but later can be used for fleet grouping
530
   */
531
  // TODO - safe IDs with check via possible fleets
532
  public function group_acs_set($acs_id, $mission_id) {
533
    $this->group_id = $acs_id;
534
    $this->mission_type = $mission_id;
535
  }
536
537
  public function shipCountById($ship_id) {
538
    return $this->unitList->unitCountById($ship_id);
539
  }
540
541
542
  public function mark_fleet_as_returned_and_save() {
543
    $this->mark_fleet_as_returned();
544
    $this->dbSave();
545
  }
546
547
  /**
548
   * Replaces current unit list from array of units
549
   *
550
   * @param array $unit_list
551
   */
552
  // TODO - DEPRECATED!
553
  public function replace_ships($unit_list) {
554
    // TODO - Resets also delta and changes?!
555
//    $this->unitList->_reset();
556
    pdie('Replace_ships should be rewritten! Deletes ships by setting their count to 0, adding ship with UnitList standard procedure');
557
    !is_array($unit_list) ? $unit_list = array() : false;
558
559
    foreach($unit_list as $unit_id => $unit_count) {
560
      // TODO - проверка на допустимые корабли
0 ignored issues
show
Unused Code Comprehensibility introduced by
41% 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
//      if(!UnitShip::is_in_group($unit_id) || !($unit_count = floor($unit_count))) {
562
//        // Not a ship - continuing
563
//        continue;
564
//      }
565
566
      $this->unitList->unitSetCount($unit_id, $unit_count);
567
    }
568
  }
569
570
571
  public function set_zero_cargo() {
572
    $this->unitSetResourceList(array(
573
      RES_METAL     => 0,
574
      RES_CRYSTAL   => 0,
575
      RES_DEUTERIUM => 0,
576
    ));
577
  }
578
579
580
  /**
581
   * Parses extended unit_array which can include not only ships but resources, captains etc
582
   *
583
   * @param $unit_array
584
   */
585
  public function unitsSetFromArray($unit_array) {
586
    foreach($unit_array as $unit_id => $unit_count) {
587
      $unit_count = floatval($unit_count);
588
      if(!$unit_count) {
589
        continue;
590
      }
591
592
      if($this->isUnit($unit_id)) {
593
        $this->unitList->unitSetCount($unit_id, $unit_count);
594
      } elseif($this->isResource($unit_id)) {
595
        $this->resource_list[$unit_id] = $unit_count;
596
      } else {
597
        throw new Exception('Trying to pass to fleet non-resource and non-ship ' . var_export($unit_array, true), ERR_ERROR);
598
      }
599
    }
600
  }
601
602
  // TODO - перекрывать пожже - для миссайл-флотов и дефенс-флотов
603
  protected function isUnit($unit_id) {
604
    return UnitShip::is_in_group($unit_id);
605
  }
606
607
  protected function isResource($unit_id) {
608
    return UnitResourceLoot::is_in_group($unit_id);
609
  }
610
611
  /**
612
   * Sets fleet timers based on flight duration, time on mission (HOLD/EXPLORE) and fleet departure time.
613
   *
614
   * @param int $time_to_travel - flight duration in seconds
615
   * @param int $time_on_mission - time on mission in seconds
616
   * @param int $group_sync_delta_time - delta time to adjust fleet arrival time if fleet is a part of group (i.e. ACS)
617
   * @param int $flight_departure - fleet departure from source planet timestamp. Allows to send fleet in future or in past
618
   */
619
  public function set_times($time_to_travel, $time_on_mission = 0, $group_sync_delta_time = 0, $flight_departure = SN_TIME_NOW) {
620
    $this->_time_launch = $flight_departure;
621
622
    $this->_time_arrive_to_target = $this->_time_launch + $time_to_travel + $group_sync_delta_time;
623
    $this->_time_mission_job_complete = $time_on_mission ? $this->_time_arrive_to_target + $time_on_mission : 0;
624
    $this->_time_return_to_source = ($this->_time_mission_job_complete ? $this->_time_mission_job_complete : $this->_time_arrive_to_target) + $time_to_travel;
625
  }
626
627
  /**
628
   * Initializes Fleet from user params and posts it to DB
629
   */
630
  public function dbInsert() {
631
    // WARNING! MISSION TIMES MUST BE SET WITH set_times() method!
632
    // TODO - more checks!
633
    if(empty($this->_time_launch)) {
634
      die('Fleet time not set!');
635
    }
636
637
    parent::dbInsert();
638
  }
639
640
  /**
641
   * Returns ship list in fleet
642
   */
643
  public function get_unit_list() {
644
    return $this->unitList->unitArrayGet();
645
  }
646
647
  /**
648
   * Returns resource list in fleet
649
   */
650
  public function get_resource_list() {
651
    return $this->resource_list;
652
  }
653
654
  /**
655
   * @param array $rate
656
   *
657
   * @return float
658
   */
659
  public function get_resources_amount_in_metal(array $rate) {
660
    return
661
      $this->resource_list[RES_METAL] * $rate[RES_METAL]
662
      + $this->resource_list[RES_CRYSTAL] * $rate[RES_CRYSTAL] / $rate[RES_METAL]
663
      + $this->resource_list[RES_DEUTERIUM] * $rate[RES_DEUTERIUM] / $rate[RES_METAL];
664
  }
665
666
  /**
667
   * Compiles object for INSERT DB command
668
   *
669
   * @return array
670
   */
671
  public function make_db_insert_set() {
672
    $db_set = array(
673
//      'fleet_id'              => $this->id,
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
674
      'fleet_owner'   => $this->_playerOwnerId,
675
      'fleet_mission' => $this->_mission_type,
676
677
      'fleet_target_owner' => !empty($this->_target_owner_id) ? $this->_target_owner_id : null,
678
      'fleet_group'        => $this->_group_id,
679
      'fleet_mess'         => empty($this->_is_returning) ? 0 : 1,
680
681
      'start_time'       => $this->_time_launch,
682
      'fleet_start_time' => $this->_time_arrive_to_target,
683
      'fleet_end_stay'   => $this->_time_mission_job_complete,
684
      'fleet_end_time'   => $this->_time_return_to_source,
685
686
      'fleet_start_planet_id' => !empty($this->_fleet_start_planet_id) ? $this->_fleet_start_planet_id : null,
687
      'fleet_start_galaxy'    => $this->_fleet_start_galaxy,
688
      'fleet_start_system'    => $this->_fleet_start_system,
689
      'fleet_start_planet'    => $this->_fleet_start_planet,
690
      'fleet_start_type'      => $this->_fleet_start_type,
691
692
      'fleet_end_planet_id' => !empty($this->_fleet_end_planet_id) ? $this->_fleet_end_planet_id : null,
693
      'fleet_end_galaxy'    => $this->_fleet_end_galaxy,
694
      'fleet_end_system'    => $this->_fleet_end_system,
695
      'fleet_end_planet'    => $this->_fleet_end_planet,
696
      'fleet_end_type'      => $this->_fleet_end_type,
697
698
      'fleet_amount' => $this->getShipCount(),
699
700
      'fleet_resource_metal'     => $this->resource_list[RES_METAL],
701
      'fleet_resource_crystal'   => $this->resource_list[RES_CRYSTAL],
702
      'fleet_resource_deuterium' => $this->resource_list[RES_DEUTERIUM],
703
    );
704
705
    return $db_set;
706
  }
707
708
  public function parse_missile_db_row($missile_db_row) {
709
//    $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...
710
711
    if(empty($missile_db_row) || !is_array($missile_db_row)) {
712
      return;
713
    }
714
715
//      $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...
716
//      $irak_original['fleet_start_name'] = $planet_start['name'];
717
    $this->missile_target = $missile_db_row['primaer'];
718
719
    $this->_dbId = -$missile_db_row['id'];
720
    $this->_playerOwnerId = $missile_db_row['fleet_owner'];
721
    $this->_mission_type = MT_MISSILE;
722
723
    $this->_target_owner_id = $missile_db_row['fleet_target_owner'];
724
725
    $this->_group_id = 0;
726
    $this->_is_returning = 0;
727
728
    $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...
729
    $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...
730
    $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...
731
    $this->_time_return_to_source = $missile_db_row['fleet_end_time'];
732
733
    $this->_fleet_start_planet_id = !empty($missile_db_row['fleet_start_planet_id']) ? $missile_db_row['fleet_start_planet_id'] : null;
734
    $this->_fleet_start_galaxy = $missile_db_row['fleet_start_galaxy'];
735
    $this->_fleet_start_system = $missile_db_row['fleet_start_system'];
736
    $this->_fleet_start_planet = $missile_db_row['fleet_start_planet'];
737
    $this->_fleet_start_type = $missile_db_row['fleet_start_type'];
738
739
    $this->_fleet_end_planet_id = !empty($missile_db_row['fleet_end_planet_id']) ? $missile_db_row['fleet_end_planet_id'] : null;
740
    $this->_fleet_end_galaxy = $missile_db_row['fleet_end_galaxy'];
741
    $this->_fleet_end_system = $missile_db_row['fleet_end_system'];
742
    $this->_fleet_end_planet = $missile_db_row['fleet_end_planet'];
743
    $this->_fleet_end_type = $missile_db_row['fleet_end_type'];
744
745
    $this->unitList->unitSetCount(UNIT_DEF_MISSILE_INTERPLANET, $missile_db_row['fleet_amount']);
746
  }
747
748
  /**
749
   * Возвращает ёмкость переработчиков во флоте
750
   *
751
   * @param array $recycler_info
752
   *
753
   * @return int
754
   *
755
   * @version 41a6.28
756
   */
757
  public function fleet_recyclers_capacity(array $recycler_info) {
758
    $recyclers_incoming_capacity = 0;
759
    $fleet_data = $this->get_unit_list();
760
    foreach($recycler_info as $recycler_id => $recycler_data) {
761
      $recyclers_incoming_capacity += $fleet_data[$recycler_id] * $recycler_data['capacity'];
762
    }
763
764
    return $recyclers_incoming_capacity;
765
  }
766
767
768
  public function getShipCount() {
769
    return $this->unitList->getSumProperty('count');
770
  }
771
772
  public function get_resources_amount() {
773
    return empty($this->resource_list) || !is_array($this->resource_list) ? 0 : array_sum($this->resource_list);
774
  }
775
776
  protected function _reset_resources() {
777
    $this->resource_list = array(
778
      RES_METAL     => 0,
779
      RES_CRYSTAL   => 0,
780
      RES_DEUTERIUM => 0,
781
    );
782
    $this->resource_delta = array();
783
    $this->resource_replace = array();
784
  }
785
786
  /**
787
   * @param $from
788
   */
789
  public function set_start_planet($from) {
790
    $this->fleet_start_planet_id = intval($from['id']) ? $from['id'] : null;
791
    $this->fleet_start_galaxy = $from['galaxy'];
792
    $this->fleet_start_system = $from['system'];
793
    $this->fleet_start_planet = $from['planet'];
794
    $this->fleet_start_type = $from['planet_type'];
795
  }
796
797
  /**
798
   * @param $to
799
   */
800
  public function set_end_planet($to) {
801
    $this->target_owner_id = intval($to['id_owner']) ? $to['id_owner'] : 0;
802
    $this->fleet_end_planet_id = intval($to['id']) ? $to['id'] : null;
803
    $this->fleet_end_galaxy = $to['galaxy'];
804
    $this->fleet_end_system = $to['system'];
805
    $this->fleet_end_planet = $to['planet'];
806
    $this->fleet_end_type = $to['planet_type'];
807
  }
808
809
810
  /**
811
   * Extracts resources value from db_row
812
   *
813
   * @param array $db_row
814
   *
815
   * @internal param Fleet $that
816
   * @version 41a6.28
817
   */
818
  protected function extractResources(array &$db_row) {
819
    $this->resource_list = array(
820
      RES_METAL     => !empty($db_row['fleet_resource_metal']) ? floor($db_row['fleet_resource_metal']) : 0,
821
      RES_CRYSTAL   => !empty($db_row['fleet_resource_crystal']) ? floor($db_row['fleet_resource_crystal']) : 0,
822
      RES_DEUTERIUM => !empty($db_row['fleet_resource_deuterium']) ? floor($db_row['fleet_resource_deuterium']) : 0,
823
    );
824
  }
825
826
  protected function injectResources(array &$db_row) {
827
    $db_row['fleet_resource_metal'] = $this->resource_list[RES_METAL];
828
    $db_row['fleet_resource_crystal'] = $this->resource_list[RES_CRYSTAL];
829
    $db_row['fleet_resource_deuterium'] = $this->resource_list[RES_DEUTERIUM];
830
  }
831
832
833
834
  // UnitList access ***************************************************************************************************
835
836
  /**
837
   * Set unit count of $unit_id to $unit_count
838
   * If there is no $unit_id - it will be created and saved to DB on dbSave
839
   *
840
   * @param int $unit_id
841
   * @param int $unit_count
842
   */
843
  public function unitSetCount($unit_id, $unit_count = 0) {
844
    $this->unitAdjustCount($unit_id, $unit_count, true);
845
  }
846
847
  /**
848
   * Adjust unit count of $unit_id by $unit_count - or just replace value
849
   * If there is no $unit_id - it will be created and saved to DB on dbSave
850
   *
851
   * @param int  $unit_id
852
   * @param int  $unit_count
853
   * @param bool $replace_value
854
   */
855
  public function unitAdjustCount($unit_id, $unit_count = 0, $replace_value = false) {
856
    $this->unitList->unitAdjustCount($unit_id, $unit_count, $replace_value);
857
  }
858
859
  // Resources access ***************************************************************************************************
860
861
//  /**
862
//   * Set unit count of $unit_id to $unit_count
863
//   * If there is no $unit_id - it will be created and saved to DB on dbSave
864
//   *
865
//   * @param int $unit_id
866
//   * @param int $unit_count
867
//   */
868
//  public function unitSetResourceList($unit_id, $unit_count = 0) {
869
//    $this->unitList->unitAdjustCount($unit_id, $unit_count, true);
870
//  }
871
//
872
//  /**
873
//   * Adjust unit count of $unit_id by $unit_count - or just replace value
874
//   * If there is no $unit_id - it will be created and saved to DB on dbSave
875
//   *
876
//   * @param int  $unit_id
877
//   * @param int  $unit_count
878
//   * @param bool $replace_value
879
//   */
880
//  public function unitAdjustResourceList($unit_id, $unit_count = 0, $replace_value = false) {
881
//    $this->unitList->unitAdjustCount($unit_id, $unit_count, $replace_value);
882
//  }
883
884
  /**
885
   * Set current resource list from array of units
886
   *
887
   * @param array $resource_list
888
   */
889
  public function unitSetResourceList($resource_list) {
890
    if(!empty($this->propertiesAdjusted['resource_list'])) {
891
      throw new PropertyAccessException('Property "resource_list" already was adjusted so no SET is possible until dbSave in ' . get_called_class() . '::unitSetResourceList', ERR_ERROR);
892
    }
893
    $this->unitAdjustResourceList($resource_list, true);
894
  }
895
896
  /**
897
   * Updates fleet resource list with deltas
898
   *
899
   * @param $resource_delta_list
900
   */
901
  public function unitAdjustResourceList($resource_delta_list, $replace_value = false) {
902
    !is_array($resource_delta_list) ? $resource_delta_list = array() : false;
903
904
    foreach($resource_delta_list as $resource_id => $unit_delta) {
905
      if(!UnitResourceLoot::is_in_group($resource_id) || !($unit_delta = floor($unit_delta))) {
906
        // Not a resource or no resources - continuing
907
        continue;
908
      }
909
910
      if($replace_value) {
911
        $this->resource_list[$resource_id] = $unit_delta;
912
      } else {
913
        $this->resource_list[$resource_id] += $unit_delta;
914
        // Preparing changes
915
        $this->resource_delta[$resource_id] += $unit_delta;
916
      }
917
918
      // Check for negative unit value
919
      if($this->resource_list[$resource_id] < 0) {
920
        // TODO
921
        throw new Exception('Resource ' . $resource_id . ' will become negative in ' . get_called_class() . '::unitAdjustResourceList', ERR_ERROR);
922
      }
923
    }
924
925
    $this->propertiesAdjusted['resource_list'] = 1;
926
927
  }
928
929
}
930