Passed
Push — work-fleets ( 4e1f0c...91349a )
by SuperNova.WS
10:40
created

flt_flying_fleet_handler2.php ➔ flt_flying_fleet_handler()   D

Complexity

Conditions 45
Paths 167

Size

Total Lines 267
Code Lines 137

Duplication

Lines 14
Ratio 5.24 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 45
eloc 137
c 3
b 0
f 0
nc 167
nop 1
dl 14
loc 267
rs 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
// ------------------------------------------------------------------
4
// unit_captain overrides
5
use DBStatic\DBStaticPlanet;
6
use DBStatic\DBStaticUser;
7
use Mission\Mission;
8
9
/**
10
 * Handled by:
11
 *    - unit_captain
12
 * Overridden by:
13
 *    - none
14
 *
15
 * @param Fleet $objFleet
16
 * @param bool  $start
17
 * @param null  $result
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
18
 *
19
 * @return mixed
20
 */
21
function RestoreFleetToPlanet(&$objFleet, $start = true) { return sn_function_call(__FUNCTION__, array(&$objFleet, $start)); }
22
23
// ------------------------------------------------------------------
24
function flt_flyingFleetsSort($a, $b) {
25
  // Сравниваем время флотов - кто раньше, тот и первый обрабатывается
26
  return $a['fleet_time'] > $b['fleet_time'] ? 1 : ($a['fleet_time'] < $b['fleet_time'] ? -1 :
27
    // Если время - одинаковое, сравниваем события флотов
28
    // Если события - одинаковые, то флоты равны
29
    ($a['fleet_event'] == $b['fleet_event'] ? 0 :
30
      // Если события разные - первыми считаем прибывающие флоты
31
      ($a['fleet_event'] == EVENT_FLT_ARRIVE ? 1 : ($b['fleet_event'] == EVENT_FLT_ARRIVE ? -1 :
32
        // Если нет прибывающих флотов - дальше считаем флоты, которые закончили миссию
33
        ($a['fleet_event'] == EVENT_FLT_ACOMPLISH ? 1 : ($b['fleet_event'] == EVENT_FLT_ACOMPLISH ? -1 :
34
          // Если нет флотов, закончивших задание - остались возвращающиеся флоты, которые равны между собой
35
          // TODO: Добавить еще проверку по ID флота и/или времени запуска - что бы обсчитывать их в порядке запуска
36
          (
37
          0 // Вообще сюда доходить не должно - будет отсекаться на равенстве событий
38
          )
39
        ))
40
      ))
41
    )
42
  );
43
}
44
45
function log_file($msg) {
46
  static $handler;
47
48
  if (!$handler) {
49
    $handler = fopen('event.log', 'a+');
50
  }
51
52
  fwrite($handler, date(FMT_DATE_TIME_SQL, time()) . ' ' . $msg . "\r\n");
53
}
54
55
// ------------------------------------------------------------------
56
function flt_flying_fleet_handler($skip_fleet_update = false) {
57
  if (true) {
0 ignored issues
show
Bug introduced by
Avoid IF statements that are always true or false
Loading history...
58
    if(!defined('IN_AJAX')) {
59
      print('<div style="color: red; font-size: 300%">Fleet handler is disabled</div>');
60
      pdump('Fleet handler is disabled');
61
    }
62
63
    return;
64
  }
65
  /*
66
67
  [*] Нужно ли заворачивать ВСЕ в одну транзакцию?
68
      С одной стороны - да, что бы данные были гарантированно на момент снапшота
69
      С другой стороны - нет, потому что при большой активности это все будет блокировать слишком много рядов, да и таймаут будет большой для ожидания всего разлоченного
70
      Стоит завернуть каждую миссию отдельно? Это сильно увеличит количество запросов, зато так же сильно снизит количество блокировок.
71
72
      Resume: НЕТ! Надо оставить все в одной транзакции! Так можно будет поддерживать consistency кэша. Там буквально сантисекунды блокировки
73
74
  [*] Убрать кэшированние данных о пользователях и планета. Офигенно освободит память - проследить!
75
      НЕТ! Считать, скольким флотам нужна будет инфа и кэшировать только то, что используется больше раза!
76
      Заодно можно будет исключить перересчет очередей/ресурсов - сильно ускорит дело!
77
      Особенно будет актуально, когда все бонусы будут в одной таблице
78
      Ну и никто не заставляет как сейчас брать ВСЕ из таблицы - только по полям. Гемор, но не сильный - сделать запрос по группам sn_data
79
      И писать в БД только один раз результат
80
81
  [*] Нужно ли на этом этапе знать полную информацию о флотах?
82
      Заблокировать флоты можно и неполным запросом. Блокировка флотов - это не страшно. Ну, не пройдет одна-две отмены - так никто и не гарантировал реалтайма!
83
      С одной стороны - да, уменьшит количество запросов
84
      С другой стооны - расход памяти
85
      Все равно надо будет знать полную инфу о флоте в момент обработки
86
87
  [*] Сделать тестовую БД для расчетов
88
89
  [*] Но не раньше, чем переписать все миссии
90
91
  */
92
93
  if (
94
    classSupernova::$config->game_disable != GAME_DISABLE_NONE
95
    ||
96
    $skip_fleet_update
97
    ||
98
    SN_TIME_NOW - strtotime(classSupernova::$config->fleet_update_last) <= classSupernova::$config->fleet_update_interval
0 ignored issues
show
Documentation introduced by
The property fleet_update_last does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
99
  ) {
100
    return;
101
  }
102
103
  sn_db_transaction_start();
104
105
  // Watchdog timer
106
  if (classSupernova::$config->db_loadItem('fleet_update_lock')) {
107
    if (defined('DEBUG_FLYING_FLEETS')) {
108
      $random = 0;
109
    } else {
110
      $random = mt_rand(90, 120);
111
    }
112
113
    if (SN_TIME_NOW - strtotime(classSupernova::$config->fleet_update_lock) <= $random) {
0 ignored issues
show
Documentation introduced by
The property fleet_update_lock does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
114
      sn_db_transaction_rollback();
115
116
      return;
117
    } else {
118
      classSupernova::$debug->warning('Flying fleet handler was locked too long - watchdog unlocked', 'FFH Error', 504);
119
    }
120
  }
121
122
  classSupernova::$config->db_saveItem('fleet_update_lock', SN_TIME_SQL);
123
  classSupernova::$config->db_saveItem('fleet_update_last', SN_TIME_SQL);
124
  sn_db_transaction_commit();
125
126
//log_file('Начинаем обсчёт флотов');
127
128
//log_file('Обсчёт ракет');
129
  sn_db_transaction_start();
130
  coe_o_missile_calculate();
131
  sn_db_transaction_commit();
132
133
  $fleet_event_list = array();
134
  $missions_used = array();
135
136
  $objFleetList = FleetList::dbGetFleetListCurrentTick();
137
  foreach ($objFleetList->_container as $objFleet) {
138
    set_time_limit(15);
139
    // TODO - Унифицировать код с темплейтным разбором эвентов на планете!
140
    $missions_used[$objFleet->mission_type] = 1;
141 View Code Duplication
    if ($objFleet->time_arrive_to_target <= SN_TIME_NOW && !$objFleet->isReturning()) {
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...
142
      $fleet_event_list[] = array(
143
        'object'      => $objFleet,
144
        'fleet_time'  => $objFleet->time_arrive_to_target,
145
        'fleet_event' => EVENT_FLT_ARRIVE,
146
      );
147
    }
148
149 View Code Duplication
    if ($objFleet->time_mission_job_complete > 0 && $objFleet->time_mission_job_complete <= SN_TIME_NOW && !$objFleet->isReturning()) {
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...
150
      $fleet_event_list[] = array(
151
        'object'      => $objFleet,
152
        'fleet_time'  => $objFleet->time_mission_job_complete,
153
        'fleet_event' => EVENT_FLT_ACOMPLISH,
154
      );
155
    }
156
157
    if ($objFleet->time_return_to_source <= SN_TIME_NOW) {
158
      $fleet_event_list[] = array(
159
        'object'      => $objFleet,
160
        'fleet_time'  => $objFleet->time_return_to_source,
161
        'fleet_event' => EVENT_FLT_RETURN,
162
      );
163
    }
164
  }
165
166
//log_file('Сортировка и подгрузка модулей');
167
  uasort($fleet_event_list, 'flt_flyingFleetsSort');
168
169
// TODO: Грузить только используемые модули из $missions_used
170
  $mission_files = array(
171
    MT_ATTACK    => 'flt_mission_attack',
172
    MT_ACS       => 'flt_mission_attack',
173
    MT_DESTROY   => 'flt_mission_attack',
174
    MT_TRANSPORT => 'flt_mission_transport',
175
    MT_RELOCATE  => 'flt_mission_relocate',
176
    MT_HOLD      => 'flt_mission_hold',
177
    MT_SPY       => 'flt_mission_spy',
178
    MT_COLONIZE  => 'flt_mission_colonize',
179
    MT_RECYCLE   => 'flt_mission_recycle',
180
//    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...
181
    MT_EXPLORE   => 'flt_mission_explore',
182
  );
183
  foreach ($missions_used as $mission_id => $cork) {
184
    require_once(SN_ROOT_PHYSICAL . "includes/includes/{$mission_files[$mission_id]}" . DOT_PHP_EX);
185
  }
186
187
//log_file('Обработка миссий');
188
  $sn_groups_mission = sn_get_groups('missions');
189
  foreach ($fleet_event_list as $fleet_event) {
190
    // Watchdog timer
191
    // If flying fleet handler works more then 10 seconds - stopping it
192
    // Let next run handle rest of fleets
193
    if(time() - SN_TIME_NOW > 10) {
194
      $debug->warning('Flying fleet handler standard routine works more then 10 seconds - watchdog unlocked', 'FFH Warning', 504);
0 ignored issues
show
Bug introduced by
The variable $debug does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
195
      break;
196
    }
197
198
    // TODO: Указатель тут потом сделать
199
    // TODO: СЕЙЧАС НАДО ПРОВЕРЯТЬ ПО БАЗЕ - А ЖИВОЙ ЛИ ФЛОТ?!
200
    if (empty($fleet_event['object'])) {
201
      // Fleet was destroyed in course of previous actions
202
      continue;
203
    }
204
205
    /**
206
     * @var Fleet $objFleet
207
     */
208
    $objFleet = $fleet_event['object'];
209
//    $objFleet = new Fleet();
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...
210
//    $objFleet->parse_db_row($fleet_row);
211
212
    // TODO Обернуть всё в транзакции. Начинать надо заранее, блокируя все таблицы внутренним локом SELECT 1 FROM {{users}}
213
    sn_db_transaction_start();
214
    classSupernova::$config->db_saveItem('fleet_update_last', SN_TIME_SQL);
215
216
217
    $mission_data = $sn_groups_mission[$objFleet->mission_type];
218
219
    // Формируем запрос, блокирующий сразу все нужные записи
220
    // TODO - два уровня блокировки. "Просто" блокировка - и для атаки
221
    $objFleet->dbLockFlying($mission_data);
222
223
    $objFleet->dbLoad($objFleet->dbId);
224
225
    if (!$objFleet->dbId) {
226
      // Fleet was destroyed in course of previous actions
227
      sn_db_transaction_commit();
228
      continue;
229
    }
230
231
    if ($fleet_event['fleet_event'] == EVENT_FLT_RETURN) {
232
      // Fleet returns to planet
233
      $objFleet->shipsLand(true);
234
      sn_db_transaction_commit();
235
      continue;
236
    }
237
238
    if ($fleet_event['fleet_event'] == EVENT_FLT_ARRIVE && $objFleet->isReturning()) {
239
      // При событии EVENT_FLT_ARRIVE флот всегда должен иметь fleet_mess == 0
240
      // В противном случае это означает, что флот уже был обработан ранее - например, при САБе
241
      sn_db_transaction_commit();
242
      continue;
243
    }
244
245
    // TODO: Здесь тоже указатели
246
    // TODO: Кэширование
247
    // TODO: Выбирать только нужные поля
248
249
    $objMission = new Mission($objFleet);
250
    $objMission->fleet = $objFleet;
251
    $objMission->src_user = $mission_data['src_user'] || $mission_data['src_planet'] ? DBStaticUser::db_user_by_id($objFleet->playerOwnerId, true) : null;
0 ignored issues
show
Documentation Bug introduced by
It seems like $mission_data['src_user'...erOwnerId, true) : null can be null. However, the property $src_user is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
252
    $objMission->src_planet = $mission_data['src_planet'] ? DBStaticPlanet::db_planet_by_vector($objFleet->launch_coordinates_typed(), '', true, '`id`, `id_owner`, `name`') : null;
253
    $objMission->dst_user = $mission_data['dst_user'] || $mission_data['dst_planet'] ? DBStaticUser::db_user_by_id($objFleet->target_owner_id, true) : null;
0 ignored issues
show
Documentation Bug introduced by
It seems like $mission_data['dst_user'..._owner_id, true) : null can be null. However, the property $dst_user is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
254
    // шпионаж не дает нормальный ID fleet_end_planet_id 'dst_planet'
255
    $objMission->dst_planet = $mission_data['dst_planet'] ? DBStaticPlanet::db_planet_by_vector($objFleet->target_coordinates_typed(), '', true, '`id`, `id_owner`, `name`') : null;
256
    $objMission->fleet_event = $fleet_event['fleet_event'];
257
258
    // Fleet that have planet destination is returned
259
    if($mission_data['dst_planet'] && empty($objMission->dst_planet['id_owner'])) {
260
      $objFleet->markReturnedAndSave();
261
      sn_db_transaction_commit();
262
      continue;
263
    }
264
265
    if (!empty($objMission->dst_planet['id_owner'])) {
266
      $update_result = sys_o_get_updated($objMission->dst_planet['id_owner'], $objMission->dst_planet['id'], $objFleet->time_arrive_to_target);
267
      $objMission->dst_user = !empty($objMission->dst_user) ? $update_result['user'] : null;
268
      $objMission->dst_planet = $update_result['planet'];
269
    }
270
271
    switch ($objFleet->mission_type) {
272
      // Для боевых атак нужно обновлять по САБу и по холду - таки надо возвращать данные из обработчика миссий!
273
      case MT_ACS:
274
      case MT_ATTACK:
275
      case MT_DESTROY:
276
        flt_mission_attack($objMission);
277
      break;
278
279
      case MT_TRANSPORT:
280
        flt_mission_transport($objMission);
281
      break;
282
283
      case MT_HOLD:
284
        flt_mission_hold($objMission);
285
      break;
286
287
      case MT_RELOCATE:
288
        flt_mission_relocate($objMission);
289
      break;
290
291
      case MT_EXPLORE:
292
        flt_mission_explore($objMission);
293
      break;
294
295
      case MT_RECYCLE:
296
        flt_mission_recycle($objMission);
297
      break;
298
299
      case MT_COLONIZE:
300
        flt_mission_colonize($objMission);
301
      break;
302
303
      case MT_SPY:
304
        flt_mission_spy($objMission);
305
      break;
306
307
      case MT_MISSILE:  // Missiles !!
308
      break;
309
310
//      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...
311
//        doDelete("DELETE FROM `{{_fleets}}` WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
312
//      break;
313
    }
314
    sn_db_transaction_commit();
315
  }
316
  sn_db_transaction_start();
317
  classSupernova::$config->db_saveItem('fleet_update_last', SN_TIME_SQL);
318
  classSupernova::$config->db_saveItem('fleet_update_lock', '');
319
  sn_db_transaction_commit();
320
321
//  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...
322
}
323