Test Failed
Push — trunk ( db071f...8d464a )
by SuperNova.WS
06:33
created

FleetDispatcher::releaseLock()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by Gorlum 15.06.2017 4:12
4
 */
5
6
/**
7
 * Class FleetDispatcher
8
 *
9
 */
10
class FleetDispatcher {
11
  /**
12
   * @var \Common\GlobalContainer $gc
13
   */
14
  protected $gc;
15
16
  /**
17
   * @var classConfig $gameConfig
18
   */
19
  protected $gameConfig;
20
21
  /**
22
   * @var debug $debug
23
   */
24
  protected $debug;
25
26
  /**
27
   * List of timed events
28
   *
29
   * [
30
   *   'start'
31
   *   'finish'
32
   * ]
33
   *
34
   * @var float[] $timers
35
   */
36
  protected $timers;
37
38
39
  public function __construct(\Common\GlobalContainer $gc) {
40
    $this->gc = $gc;
41
42
    $this->gameConfig = $gc->config;
0 ignored issues
show
Documentation introduced by
The property config does not exist on object<Common\GlobalContainer>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
43
    $this->debug = $gc->debug;
0 ignored issues
show
Documentation introduced by
The property debug does not exist on object<Common\GlobalContainer>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
44
  }
45
46
  public function dispatch() {
47
    if (
48
      classSupernova::$options['fleet_update_skip']
49
      ||
50
      classSupernova::gameIsDisabled()
51
      ||
52
      !$this->getLock()
53
    ) {
54
      return;
55
    }
56
57
    $this->flt_flying_fleet_handler();
58
59
    $this->releaseLock();
60
61
    set_time_limit(60);
62
  }
63
64
65
  /**
66
   * @return bool
67
   */
68
  protected function getLock() {
69
    sn_db_transaction_start();
70
71
    // Watchdog timer
72
    if ($this->gameConfig->db_loadItem('fleet_update_lock')) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->gameConfig->db_lo...em('fleet_update_lock') of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
73
//      var_dump($this->gameConfig->db_loadItem('fleet_update_lock'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
74
//      var_dump(SN_TIME_NOW - strtotime($this->gameConfig->fleet_update_lock));
75
//      if (SN_TIME_NOW - strtotime($this->gameConfig->fleet_update_lock) <= mt_rand(90, 120)) {
76
      if (SN_TIME_NOW - strtotime($this->gameConfig->fleet_update_lock) <= mt_rand(20, 40)) {
77
        sn_db_transaction_rollback();
78
79
        return false;
80
      } else {
81
        $this->debug->warning('Fleet dispatcher was locked too long - watchdog unlocked', 'FFH Error', 504);
82
      }
83
    }
84
85
    $this->gameConfig->db_saveItem('fleet_update_last', SN_TIME_SQL);
86
    $this->gameConfig->db_saveItem('fleet_update_lock', SN_TIME_SQL);
87
    sn_db_transaction_commit();
88
89
    return true;
90
  }
91
92
  protected function releaseLock() {
93
    sn_db_transaction_start();
94
    $this->gameConfig->db_saveItem('fleet_update_lock', '');
95
    sn_db_transaction_commit();
96
  }
97
98
  /**
99
   * Gets active fleets on current tick for Flying Fleet Handler
100
   *
101
   * @return array
102
   */
103
  protected function fleet_list_current_tick() {
104
    return db_fleet_list(
105
      "
106
    (`fleet_start_time` <= " . SN_TIME_NOW . " AND `fleet_mess` = 0)
107
    OR
108
    (`fleet_end_stay` <= " . SN_TIME_NOW . " AND `fleet_end_stay` > 0 AND `fleet_mess` = 0)
109
    OR
110
    (`fleet_end_time` <= " . SN_TIME_NOW . ")"
111
      , DB_SELECT_PLAIN
112
    );
113
  }
114
115
116
  // ------------------------------------------------------------------
117
  protected function flt_flying_fleet_handler() {
118
    /*
119
120
    [*] Нужно ли заворачивать ВСЕ в одну транзакцию?
121
        С одной стороны - да, что бы данные были гарантированно на момент снапшота
122
        С другой стороны - нет, потому что при большой активности это все будет блокировать слишком много рядов, да и таймаут будет большой для ожидания всего разлоченного
123
        Стоит завернуть каждую миссию отдельно? Это сильно увеличит количество запросов, зато так же сильно снизит количество блокировок.
124
125
        Resume: НЕТ! Надо оставить все в одной транзакции! Так можно будет поддерживать consistency кэша. Там буквально сантисекунды блокировки
126
127
    [*] Убрать кэшированние данных о пользователях и планета. Офигенно освободит память - проследить!
128
        НЕТ! Считать, скольким флотам нужна будет инфа и кэшировать только то, что используется больше раза!
129
        Заодно можно будет исключить перересчет очередей/ресурсов - сильно ускорит дело!
130
        Особенно будет актуально, когда все бонусы будут в одной таблице
131
        Ну и никто не заставляет как сейчас брать ВСЕ из таблицы - только по полям. Гемор, но не сильный - сделать запрос по группам sn_data
132
        И писать в БД только один раз результат
133
134
    [*] Нужно ли на этом этапе знать полную информацию о флотах?
135
        Заблокировать флоты можно и неполным запросом. Блокировка флотов - это не страшно. Ну, не пройдет одна-две отмены - так никто и не гарантировал реалтайма!
136
        С одной стороны - да, уменьшит количество запросов
137
        С другой стооны - расход памяти
138
        Все равно надо будет знать полную инфу о флоте в момент обработки
139
140
    [*] Сделать тестовую БД для расчетов
141
142
    [*] Но не раньше, чем переписать все миссии
143
144
    */
145
    global $config, $debug, $lang;
146
147
    $workBegin = microtime(true);
148
//log_file('Начинаем обсчёт флотов');
149
150
//log_file('Обсчёт ракет');
151
    sn_db_transaction_start();
152
    coe_o_missile_calculate();
153
    sn_db_transaction_commit();
154
155
    $fleet_list = array();
156
    $fleet_event_list = array();
157
    $missions_used = array();
158
159
    $fleet_list_current_tick = $this->fleet_list_current_tick();
160
    foreach ($fleet_list_current_tick as $fleet_row) {
161
      set_time_limit(15);
162
      // TODO - Унифицировать код с темплейтным разбором эвентов на планете!
163
      $fleet_list[$fleet_row['fleet_id']] = $fleet_row;
164
      $missions_used[$fleet_row['fleet_mission']] = 1;
165 View Code Duplication
      if ($fleet_row['fleet_start_time'] <= SN_TIME_NOW && $fleet_row['fleet_mess'] == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
166
        $fleet_event_list[] = array(
167
          'fleet_row'   => &$fleet_list[$fleet_row['fleet_id']],
168
          'fleet_time'  => $fleet_list[$fleet_row['fleet_id']]['fleet_start_time'],
169
          'fleet_event' => EVENT_FLT_ARRIVE,
170
        );
171
      }
172
173 View Code Duplication
      if ($fleet_row['fleet_end_stay'] > 0 && $fleet_row['fleet_end_stay'] <= SN_TIME_NOW && $fleet_row['fleet_mess'] == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
174
        $fleet_event_list[] = array(
175
          'fleet_row'   => &$fleet_list[$fleet_row['fleet_id']],
176
          'fleet_time'  => $fleet_list[$fleet_row['fleet_id']]['fleet_end_stay'],
177
          'fleet_event' => EVENT_FLT_ACOMPLISH,
178
        );
179
      }
180
181 View Code Duplication
      if ($fleet_row['fleet_end_time'] <= SN_TIME_NOW) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
182
        $fleet_event_list[] = array(
183
          'fleet_row'   => &$fleet_list[$fleet_row['fleet_id']],
184
          'fleet_time'  => $fleet_list[$fleet_row['fleet_id']]['fleet_end_time'],
185
          'fleet_event' => EVENT_FLT_RETURN,
186
        );
187
      }
188
    }
189
190
    set_time_limit(5);
191
//log_file('Сортировка и подгрузка модулей');
192
    uasort($fleet_event_list, array($this, 'flt_flyingFleetsSort'));
193
//  unset($fleets_query);
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...
194
195
// TODO: Грузить только используемые модули из $missions_used
196
    $mission_files = array(
197
      MT_ATTACK  => 'flt_mission_attack',
198
      MT_AKS     => 'flt_mission_attack',
199
      // MT_DESTROY => 'flt_mission_destroy.php',
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
200
      MT_DESTROY => 'flt_mission_attack',
201
202
      MT_TRANSPORT => 'flt_mission_transport',
203
      MT_RELOCATE  => 'flt_mission_relocate',
204
      MT_HOLD      => 'flt_mission_hold',
205
      MT_SPY       => 'flt_mission_spy',
206
      MT_COLONIZE  => 'flt_mission_colonize',
207
      MT_RECYCLE   => 'flt_mission_recycle',
208
//    MT_MISSILE => 'flt_mission_missile.php',
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
209
      MT_EXPLORE   => 'flt_mission_explore',
210
    );
211
    foreach ($missions_used as $mission_id => $cork) {
212
      require_once(SN_ROOT_PHYSICAL . "includes/includes/{$mission_files[$mission_id]}" . DOT_PHP_EX);
213
    }
214
215
216
//log_file('Обработка миссий');
217
    $lastEventBegin = microtime(true);
218
    $lastMission = MT_NONE;
219
    $eventsProcessed = 0;
220
    $lastEvent = EVENT_FLEET_NONE;
221
222
    $sn_groups_mission = sn_get_groups('missions');
223
    foreach ($fleet_event_list as $fleet_event) {
224
      $lastEventEnd = microtime(true);
225
      // Watchdog timer
226
      // If flying fleet handler works more then 10 seconds - stopping it
227
      // Let next run handle rest of fleets
228
      $workTime = microtime(true) - $workBegin;
229
      if ($workTime > GAME_FLEET_HANDLER_MAX_TIME) {
230
        $debug->warning(sprintf(
231
          'Flying fleet handler works %1$s (> %2$s) seconds - skip rest. Processed %3$d events. Last event: mission %4$s event %6$s (%5$ss)',
232
          number_format($workTime, 4),
233
          GAME_FLEET_HANDLER_MAX_TIME,
234
          $eventsProcessed,
235
          $lang['type_mission'][$lastMission],
236
          number_format($lastEventEnd - $lastEventBegin, 4),
237
          $lang['fleet_events'][$lastEvent]
238
        ),
239
          'FFH Warning',
240
          504
241
        );
242
        break;
243
      }
244
245
      // TODO: Указатель тут потом сделать
246
      // TODO: СЕЙЧАС НАДО ПРОВЕРЯТЬ ПО БАЗЕ - А ЖИВОЙ ЛИ ФЛОТ?!
247
      $fleet_row = $fleet_event['fleet_row'];
248
      if (!$fleet_row) {
249
        // Fleet was destroyed in course of previous actions
250
        continue;
251
      }
252
253
      $lastEventBegin = microtime(true);
254
      $lastMission = $fleet_row['fleet_mission'];
255
      $lastEvent = $fleet_event['fleet_event'];
256
      $eventsProcessed++;
257
258
//log_file('Миссия');
259
      // TODO Обернуть всё в транзакции. Начинать надо заранее, блокируя все таблицы внутренним локом SELECT 1 FROM {{users}}
260
      sn_db_transaction_start();
261
      // а текущее время
262
      $config->db_saveItem('fleet_update_last', date(FMT_DATE_TIME_SQL, time()));
263
264
      $mission_data = $sn_groups_mission[$fleet_row['fleet_mission']];
265
      // Формируем запрос, блокирующий сразу все нужные записи
266
267
      db_fleet_lock_flying($fleet_row['fleet_id'], $mission_data);
268
269
//    $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE fleet_id = {$fleet_row['fleet_id']} FOR UPDATE", true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
270
      $fleet_row = db_fleet_get($fleet_row['fleet_id']);
271
      if (!$fleet_row || empty($fleet_row)) {
272
        // Fleet was destroyed in course of previous actions
273
        sn_db_transaction_commit();
274
        continue;
275
      }
276
277
      if ($fleet_event['fleet_event'] == EVENT_FLT_RETURN) {
278
        // Fleet returns to planet
279
        RestoreFleetToPlanet($fleet_row, true, false, true);
0 ignored issues
show
Deprecated Code introduced by
The function RestoreFleetToPlanet() has been deprecated.

This function has been deprecated.

Loading history...
280
        sn_db_transaction_commit();
281
        continue;
282
      }
283
284
      if ($fleet_event['fleet_event'] == EVENT_FLT_ARRIVE && $fleet_row['fleet_mess'] != 0) {
285
        // При событии EVENT_FLT_ARRIVE флот всегда должен иметь fleet_mess == 0
286
        // В противном случае это означает, что флот уже был обработан ранее - например, при САБе
287
        sn_db_transaction_commit();
288
        continue;
289
      }
290
291
      // TODO: Здесь тоже указатели
292
      // TODO: Кэширование
293
      // TODO: Выбирать только нужные поля
294
295
      // шпионаж не дает нормальный ID fleet_end_planet_id 'dst_planet'
296
      $mission_data = array(
297
        'fleet'       => &$fleet_row,
298
        'dst_user'    => $mission_data['dst_user'] || $mission_data['dst_planet'] ? db_user_by_id($fleet_row['fleet_target_owner'], true) : null,
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() has been deprecated.

This function has been deprecated.

Loading history...
299
        // TODO 'dst_planet' => $mission_data['dst_planet'] ? db_planet_by_id($fleet_row['fleet_end_planet_id'], true) : null,
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
300
        'dst_planet'  => $mission_data['dst_planet'] ? DBStaticPlanet::db_planet_by_vector($fleet_row, 'fleet_end_', true, '`id`, `id_owner`, `name`') : null,
301
        'src_user'    => $mission_data['src_user'] || $mission_data['src_planet'] ? db_user_by_id($fleet_row['fleet_owner'], true) : null,
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() has been deprecated.

This function has been deprecated.

Loading history...
302
        // TODO 'src_planet' => $mission_data['src_planet'] ? db_planet_by_id($fleet_row['fleet_start_planet_id'], true) : null,
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
303
        'src_planet'  => $mission_data['src_planet'] ? DBStaticPlanet::db_planet_by_vector($fleet_row, 'fleet_start_', true, '`id`, `id_owner`, `name`') : null,
304
        'fleet_event' => $fleet_event['fleet_event'],
305
      );
306
307
      if ($mission_data['dst_planet']) {
308
        // $mission_data['dst_planet'] = sys_o_get_updated($mission_data['dst_user'], $mission_data['dst_planet']['id'], $fleet_row['fleet_start_time']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% 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...
309
        if ($mission_data['dst_planet']['id_owner']) {
310
          $mission_data['dst_planet'] = sys_o_get_updated($mission_data['dst_planet']['id_owner'], $mission_data['dst_planet']['id'], $fleet_row['fleet_start_time']);
311
        }
312
        $mission_data['dst_user'] = $mission_data['dst_user'] ? $mission_data['dst_planet']['user'] : null;
313
        $mission_data['dst_planet'] = $mission_data['dst_planet']['planet'];
314
      }
315
316
      switch ($fleet_row['fleet_mission']) {
317
        // Для боевых атак нужно обновлять по САБу и по холду - таки надо возвращать данные из обработчика миссий!
318
        case MT_AKS:
319
        case MT_ATTACK:
320
        case MT_DESTROY:
321
          $attack_result = flt_mission_attack($mission_data);
0 ignored issues
show
Unused Code introduced by
$attack_result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
322
          $mission_result = CACHE_COMBAT;
0 ignored issues
show
Unused Code introduced by
$mission_result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
323
        break;
324
325
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
44% 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...
326
        case MT_DESTROY:
327
          $attack_result = flt_mission_destroy($mission_data);
328
          $mission_result = CACHE_COMBAT;
329
        break;
330
        */
331
332
        case MT_TRANSPORT:
333
          $mission_result = flt_mission_transport($mission_data);
0 ignored issues
show
Unused Code introduced by
$mission_result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
334
        break;
335
336
        case MT_HOLD:
337
          $mission_result = flt_mission_hold($mission_data);
0 ignored issues
show
Unused Code introduced by
$mission_result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
338
        break;
339
340
        case MT_RELOCATE:
341
          $mission_result = flt_mission_relocate($mission_data);
0 ignored issues
show
Unused Code introduced by
$mission_result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
342
        break;
343
344
        case MT_EXPLORE:
345
          $mission_result = flt_mission_explore($mission_data);
0 ignored issues
show
Unused Code introduced by
$mission_result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
346
        break;
347
348
        case MT_RECYCLE:
349
          $mission_result = flt_mission_recycle($mission_data);
0 ignored issues
show
Unused Code introduced by
$mission_result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
350
        break;
351
352
        case MT_COLONIZE:
353
          $mission_result = flt_mission_colonize($mission_data);
0 ignored issues
show
Unused Code introduced by
$mission_result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
354
        break;
355
356
        case MT_SPY:
357
          $mission_result = flt_mission_spy($mission_data);
0 ignored issues
show
Unused Code introduced by
$mission_result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
358
        break;
359
360
        case MT_MISSILE:  // Missiles !!
361
        break;
362
363
//      default:
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
364
//        doquery("DELETE FROM `{{fleets}}` WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
365
//      break;
366
      }
367
      sn_db_transaction_commit();
368
    }
369
370
//  log_file('Закончили обсчёт флотов');
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
371
  }
372
373
374
  /**
375
   * @param array $fleet_row
376
   * @param bool  $start
377
   * @param bool  $only_resources
378
   * @param bool  $safe_fleet
379
   * @param mixed $result
380
   *
381
   * @return int
382
   * @deprecated
383
   */
384
  public function sn_RestoreFleetToPlanet(&$fleet_row, $start = true, $only_resources = false, $safe_fleet = false, &$result) {
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...
385
    sn_db_transaction_check(true);
386
387
    $result = CACHE_NOTHING;
388
    if (!is_array($fleet_row)) {
389
      return $result;
390
    }
391
392
    $prefix = $start ? 'start' : 'end';
393
394
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
395
    // TODO Проеверить от многократного срабатывания !!!
396
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
397
//  $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1", true);
398
    // Узнаем ИД владельца планеты - без блокировки
399
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
400
    $user_id = DBStaticPlanet::db_planet_by_vector($fleet_row, "fleet_{$prefix}_", false, 'id_owner');
401
    $user_id = $user_id['id_owner'];
402
    // Блокируем пользователя
403
    $user = db_user_by_id($user_id, true);
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() has been deprecated.

This function has been deprecated.

Loading history...
404
    // Блокируем планету
405
    $planet_arrival = DBStaticPlanet::db_planet_by_vector($fleet_row, "fleet_{$prefix}_", true);
406
    // Блокируем флот
0 ignored issues
show
Unused Code Comprehensibility introduced by
39% 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...
407
//  $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1 FOR UPDATE;", true);
408
409
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
410
    if (!$fleet_row || !is_array($fleet_row) || ($fleet_row['fleet_mess'] == 1 && $only_resources)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fleet_row of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
411
      return $result;
412
    }
413
414
    // Флот, который возвращается на захваченную планету, пропадает
415
    if ($start && $fleet_row['fleet_mess'] == 1 && $planet_arrival['id_owner'] != $fleet_row['fleet_owner']) {
416
      db_fleet_delete($fleet_row['fleet_id']);
417
418
      return $result;
419
    }
420
421
    $db_changeset = array();
422
    if (!$only_resources) {
423
      db_fleet_delete($fleet_row['fleet_id']);
424
425
      if ($fleet_row['fleet_owner'] == $planet_arrival['id_owner']) {
426
        $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
427
        foreach ($fleet_array as $ship_id => $ship_count) {
428
          if ($ship_count) {
429
            $db_changeset['unit'][] = OldDbChangeSet::db_changeset_prepare_unit($ship_id, $ship_count, $user, $planet_arrival['id']);
0 ignored issues
show
Deprecated Code introduced by
The method OldDbChangeSet::db_changeset_prepare_unit() has been deprecated.

This method has been deprecated.

Loading history...
430
          }
431
        }
432
      } else {
433
        return CACHE_NOTHING;
434
      }
435
    } else {
436
      $fleet_set = array(
437
        'fleet_resource_metal'     => 0,
438
        'fleet_resource_crystal'   => 0,
439
        'fleet_resource_deuterium' => 0,
440
        'fleet_mess'               => 1,
441
      );
442
      fleet_update_set($fleet_row['fleet_id'], $fleet_set);
443
    }
444
445
    if (!empty($db_changeset)) {
446
      OldDbChangeSet::db_changeset_apply($db_changeset);
0 ignored issues
show
Deprecated Code introduced by
The method OldDbChangeSet::db_changeset_apply() has been deprecated.

This method has been deprecated.

Loading history...
447
    }
448
449
    DBStaticPlanet::db_planet_set_by_id($planet_arrival['id'],
450
      "`metal` = `metal` + '{$fleet_row['fleet_resource_metal']}', `crystal` = `crystal` + '{$fleet_row['fleet_resource_crystal']}', `deuterium` = `deuterium` + '{$fleet_row['fleet_resource_deuterium']}'");
451
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
452
453
    return $result;
454
  }
455
456
457
  /**
458
   * Sort flying fleets events by time+event
459
   *
460
   * @param $a
461
   * @param $b
462
   *
463
   * @return int
464
   */
465
  protected function flt_flyingFleetsSort($a, $b) {
466
    return
467
      // Сравниваем время флотов - кто раньше, тот и первый обрабатывается
468
      $a['fleet_time'] > $b['fleet_time'] ? 1 : ($a['fleet_time'] < $b['fleet_time'] ? -1 :
469
        // Если время - одинаковое, сравниваем события флотов
470
        // Если события - одинаковые, то флоты равны
471
        ($a['fleet_event'] == $b['fleet_event'] ? 0 :
472
          // Если события разные - первыми считаем прибывающие флоты
473
          ($a['fleet_event'] == EVENT_FLT_ARRIVE ? 1 : ($b['fleet_event'] == EVENT_FLT_ARRIVE ? -1 :
474
            // Если нет прибывающих флотов - дальше считаем флоты, которые закончили миссию
475
            ($a['fleet_event'] == EVENT_FLT_ACOMPLISH ? 1 : ($b['fleet_event'] == EVENT_FLT_ACOMPLISH ? -1 :
476
              // Если нет флотов, закончивших задание - остались возвращающиеся флоты, которые равны между собой
477
              // TODO: Добавить еще проверку по ID флота и/или времени запуска - что бы обсчитывать их в порядке запуска
478
              (
479
              0 // Вообще сюда доходить не должно - будет отсекаться на равенстве событий
480
              )
481
            ))
482
          ))
483
        )
484
      );
485
  }
486
487
  /**
488
   * @param string $msg
489
   */
490
  protected function log_file($msg) {
491
    static $handler;
492
493
    if (!$handler) {
494
      $handler = fopen('event.log', 'a+');
495
    }
496
497
    fwrite($handler, date(FMT_DATE_TIME_SQL, time()) . ' ' . $msg . "\r\n");
498
  }
499
500
}
501