Completed
Push — work-fleets ( fff2b6...e0e753 )
by SuperNova.WS
06:54
created

qst_quest.php ➔ qst_render_page()   F

Complexity

Conditions 24
Paths 8736

Size

Total Lines 137
Code Lines 90

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 24
eloc 90
nc 8736
nop 0
dl 0
loc 137
rs 2
c 5
b 0
f 0

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
function qst_render_page() {
4
  global $user, $template;
5
6
  $user_id = sys_get_param_id('user_id', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7
  $mode = sys_get_param_str('mode');
8
9
  $quest_units_allowed = sn_get_groups(array('structures', 'tech', 'fleet', 'defense'));
10
  $quest_reward_allowed = sn_get_groups('quest_rewards');
11
12
  $in_admin = defined('IN_ADMIN') && IN_ADMIN === true;
13
14
  if ($in_admin) {
15
    $quest_id = sys_get_param_id('id');
16
    $quest_name = sys_get_param_str_unsafe('QUEST_NAME');
17
    if (!empty($quest_name)) {
18
      $quest_description = sys_get_param_str_unsafe('QUEST_DESCRIPTION');
19
      try {
20
        $quest_rewards_list = sys_get_param('QUEST_REWARDS_LIST');
21
        $quest_rewards = array();
22
        foreach ($quest_rewards_list as $quest_rewards_id => $quest_rewards_amount) {
0 ignored issues
show
Bug introduced by
The expression $quest_rewards_list of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
23
          if (!in_array($quest_rewards_id, $quest_reward_allowed)) {
24
            throw new Exception(classLocale::$lang['qst_adm_err_reward_type']);
25
          }
26
27
          if ($quest_rewards_amount < 0) {
28
            throw new Exception(classLocale::$lang['qst_adm_err_reward_amount']);
29
          } elseif ($quest_rewards_amount > 0) {
30
            $quest_rewards[] = "{$quest_rewards_id},{$quest_rewards_amount}";
31
          }
32
        }
33
        if (empty($quest_rewards)) {
34
          throw new Exception(classLocale::$lang['qst_adm_err_reward_empty']);
35
        }
36
37
        $quest_rewards = implode(';', $quest_rewards);
38
39
        $quest_unit_id = sys_get_param_int('QUEST_UNIT_ID');
40
        if (!in_array($quest_unit_id, $quest_units_allowed)) {
41
          throw new Exception(classLocale::$lang['qst_adm_err_unit_id']);
42
        }
43
44
        $quest_unit_amount = sys_get_param_float('QUEST_UNIT_AMOUNT');
45
        if ($quest_unit_amount <= 0) {
46
          throw new Exception(classLocale::$lang['qst_adm_err_unit_amount']);
47
        }
48
        $quest_conditions = "{$quest_unit_id},{$quest_unit_amount}";
49
50
        // TODO: Change quest type
51
        $quest_type = 0;
52
53
        if ($mode == 'edit') {
54
          $quest_name = db_escape($quest_name);
55
          $quest_description = db_escape($quest_description);
56
          db_quest_update($quest_name, $quest_type, $quest_description, $quest_conditions, $quest_rewards, $quest_id);
57
        } else {
58
          sn_db_perform('{{quest}}', array(
59
            'quest_name'        => $quest_name,
60
            'quest_type'        => $quest_type,
61
            'quest_description' => $quest_description,
62
            'quest_conditions'  => $quest_conditions,
63
            'quest_rewards'     => $quest_rewards,
64
          ));
65
        }
66
67
        // TODO: Add mass mail for new quests
68
      } catch (Exception $e) {
69
        message($e->getMessage(), classLocale::$lang['sys_error']);
70
      }
71
72
      $mode = '';
73
    };
74
75
    switch ($mode) {
76
      case 'del':
77
        db_quest_delete($quest_id);
78
        $mode = '';
79
      break;
80
81
      case 'edit':
82
        $template->assign_var('QUEST_ID', $quest_id);
83
84
      case 'copy':
85
        $quest = db_quest_get($quest_id);
86
      break;
87
    }
88
    $query = db_quest_count();
89
    classSupernova::$config->db_saveItem('quest_total', $query['count']);
90
  } elseif (!$user_id) {
91
    $user_id = $user['id'];
92
  }
93
94
  $quest_list = qst_get_quests($user_id);
95
  $template->assign_vars(array(
96
    'AUTHLEVEL' => $user['authlevel'],
97
    'TOTAL'     => count($quest_list),
98
    'mode'      => $mode,
99
    'USER_ID'   => $user_id,
100
    'IN_ADMIN'  => $in_admin,
101
  ));
102
103
  if (!empty($quest)) {
104
    $quest_templatized = qst_templatize(qst_quest_parse($quest));
105
  } else {
106
    $quest_templatized['quest_rewards_list'] = array();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$quest_templatized was never initialized. Although not strictly required by PHP, it is generally a good practice to add $quest_templatized = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
107
  }
108
109
  foreach ($quest_reward_allowed as $unit_id) {
110
    $found = false;
111
    foreach ($quest_templatized['quest_rewards_list'] as $quest_templatized_reward) {
112
      if ($quest_templatized_reward['ID'] == $unit_id) {
113
        $found = true;
114
        break;
115
      }
116
    }
117
118
    if (!$found) {
119
      $quest_templatized['quest_rewards_list'][$unit_id] = array(
120
        'ID'     => $unit_id,
121
        'NAME'   => classLocale::$lang['tech'][$unit_id],
122
        'AMOUNT' => 0,
123
      );
124
    }
125
  }
126
127
  qst_assign_to_template($template, $quest_templatized);
128
129
  foreach ($quest_list as $quest_data) {
130
    qst_assign_to_template($template, qst_templatize($quest_data, true), 'quest');
0 ignored issues
show
Documentation introduced by
'quest' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
131
  }
132
133
  foreach ($quest_units_allowed as $unit_id) {
134
    $template->assign_block_vars('allowed_unit', array(
135
      'ID'   => $unit_id,
136
      'NAME' => classLocale::$lang['tech'][$unit_id],
137
    ));
138
  }
139
}
140
141
function qst_get_quests($user_id = false, $status = false) {
142
  $quest_list = array();
143
144
  $query_add_select = '';
145
  $query_add_from = '';
146
  $query_add_where = '';
147
148
  if ($user_id) {
149
    if ($status !== false) {
150
      $query_add_where = "AND qs.quest_status_status ";
151
      if ($status == null) {
152
        $query_add_where .= "IS NULL";
153
      } else {
154
        $query_add_where .= "= {$status}";
155
      }
156
    }
157
    $query_add_select = ", qs.quest_status_progress, qs.quest_status_status";
158
    $query_add_from = "LEFT JOIN {{quest_status}} AS qs ON qs.quest_status_quest_id = q.quest_id AND qs.quest_status_user_id = {$user_id}";
159
  }
160
161
  $query = db_quest_list_get($query_add_select, $query_add_from, $query_add_where);
162
163
  while ($quest = db_fetch($query)) {
164
    $quest_list[$quest['quest_id']] = qst_quest_parse($quest);
165
  }
166
167
  return $quest_list;
168
}
169
170
/**
171
 * @param template $template
172
 * @param          $quest_templatized
173
 * @param bool     $block_name
174
 */
175
function qst_assign_to_template(&$template, $quest_templatized, $block_name = false) {
176
  if ($block_name) {
177
    $template->assign_block_vars($block_name, $quest_templatized);
178
  } else {
179
    $template->assign_vars($quest_templatized);
180
    if (!empty($quest_templatized['quest_rewards_list'])) {
181
      foreach ($quest_templatized['quest_rewards_list'] as $quest_reward) {
182
        $template->assign_block_vars(($block_name ? $block_name . '.' : '') . 'quest_rewards_list', $quest_reward);
183
      }
184
    }
185
  }
186
}
187
188
function qst_quest_parse($quest) {
189
  list($quest['quest_unit_id'], $quest['quest_unit_amount']) = explode(',', $quest['quest_conditions']);
190
191
  $quest['quest_rewards_list'] = sys_unit_str2arr($quest['quest_rewards']);
192
193
  return $quest;
194
}
195
196
function qst_templatize($quest, $for_display = true) {
197
  $tmp = array();
198
  foreach ($quest['quest_rewards_list'] as $quest_reward_id => $quest_reward_amount) {
199
    $tmp[] = array(
200
      'ID'     => $quest_reward_id,
201
      'NAME'   => $for_display ? str_replace(' ', '&nbsp;', classLocale::$lang['tech'][$quest_reward_id]) : classLocale::$lang['tech'][$quest_reward_id],
202
      'AMOUNT' => $quest_reward_amount,
203
    );
204
  }
205
206
  return array(
207
    'QUEST_ID'           => $quest['quest_id'],
208
    'QUEST_NAME'         => $quest['quest_name'],
209
    'QUEST_TYPE'         => $quest['quest_type'],
210
    'QUEST_DESCRIPTION'  => $for_display ? sys_bbcodeParse($quest['quest_description']) : $quest['quest_description'],
211
    'QUEST_CONDITIONS'   => $quest['quest_condition'],
212
    'QUEST_UNIT_ID'      => $quest['quest_unit_id'],
213
    'QUEST_UNIT_NAME'    => classLocale::$lang['tech'][$quest['quest_unit_id']],
214
    'QUEST_UNIT_AMOUNT'  => $quest['quest_unit_amount'],
215
    'QUEST_STATUS'       => intval($quest['quest_status_status']),
216
    'QUEST_STATUS_NAME'  => classLocale::$lang['qst_status_list'][intval($quest['quest_status_status'])],
217
    'quest_rewards_list' => $tmp,
218
  );
219
}
220
221
function qst_active_triggers($quest_list) {
222
  $quest_triggers = array();
223
  foreach ($quest_list as $quest_id => $quest) {
224
    if ($quest['quest_status_status'] != QUEST_STATUS_COMPLETE) {
225
      list($quest_unit_id, $quest_unit_amount) = explode(',', $quest['quest_conditions']);
0 ignored issues
show
Unused Code introduced by
The assignment to $quest_unit_amount is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
226
      $quest_triggers[$quest_id] = $quest_unit_id;
227
    }
228
  }
229
230
  return $quest_triggers;
231
}
232
233
function qst_reward(&$user, &$rewards, &$quest_list) {
234
  if (empty($rewards)) {
235
    return;
236
  }
237
238
  $classLocale = classLocale::$lang;
239
240
  $db_changeset = array();
241
  $total_rewards = array();
242
  $comment_dm = '';
243
244
  foreach ($rewards as $quest_id => $user_data) {
245
    foreach ($user_data as $user_id => $planet_data) {
246
      foreach ($planet_data as $planet_id => $reward_list) {
247
        $comment = sprintf(classLocale::$lang['qst_msg_complete_body'], $quest_list[$quest_id]['quest_name']);
248
        $comment_dm .= isset($reward_list[RES_DARK_MATTER]) ? $comment : '';
249
250
        $comment_reward = array();
251
        foreach ($reward_list as $unit_id => $unit_amount) {
252
          $comment_reward[] = $unit_amount . ' ' . classLocale::$lang['tech'][$unit_id];
253
          $total_rewards[$user_id][$planet_id][$unit_id] += $unit_amount;
254
        }
255
        $comment .= " {$classLocale['qst_msg_your_reward']} " . implode(',', $comment_reward);
256
257
        msg_send_simple_message($user['id'], 0, SN_TIME_NOW, MSG_TYPE_ADMIN, classLocale::$lang['msg_from_admin'], classLocale::$lang['qst_msg_complete_subject'], $comment);
258
259
        sn_db_perform('{{quest_status}}', array(
260
          'quest_status_quest_id' => $quest_id,
261
          'quest_status_user_id'  => $user_id,
262
          'quest_status_status'   => QUEST_STATUS_COMPLETE
263
        ));
264
      }
265
    }
266
  }
267
268
  $group_resources = sn_get_groups('resources_loot');
269
  $quest_rewards_allowed = sn_get_groups('quest_rewards');
270
  if (!empty($total_rewards)) {
271
    foreach ($total_rewards as $user_id => $planet_data) {
272
      $user_row = classSupernova::db_get_record_by_id(LOC_USER, $user_id);
273
      foreach ($planet_data as $planet_id => $unit_data) {
274
        $local_changeset = array();
275
        foreach ($unit_data as $unit_id => $unit_amount) {
276
          if (!isset($quest_rewards_allowed[$unit_id])) {
277
            continue;
278
          }
279
280
          if ($unit_id == RES_DARK_MATTER) {
281
            rpg_points_change($user['id'], RPG_QUEST, $unit_amount, $comment_dm);
282
          } elseif (isset($group_resources[$unit_id])) {
283
            $local_changeset[pname_resource_name($unit_id)] = array('delta' => $unit_amount);
284
          } else // Проверим на юниты
285
          {
286
            $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, $unit_amount, $user_row, $planet_id);
287
          }
288
          // unit
289
        }
290
291
        if (!empty($local_changeset)) {
292
          $planet_id = $planet_id == 0 && isset($user_row['id_planet']) ? $user_row['id_planet'] : $planet_id;
293
          $db_changeset[$planet_id ? 'planets' : 'users'][] = array(
294
            'action'  => SQL_OP_UPDATE,
295
            P_VERSION => 1,
296
            'where'   => array(
297
              "id" => $planet_id ? $planet_id : $user_id,
298
            ),
299
            'fields'  => $local_changeset,
300
          );
301
        }
302
      }
303
    }
304
305
    classSupernova::db_changeset_apply($db_changeset);
306
  }
307
}
308
309
function get_quest_amount_complete($user_id) {
310
  // TODO: Make it faster - rewrite SQL?
311
  return count(qst_get_quests($user_id, QUEST_STATUS_COMPLETE));
0 ignored issues
show
Documentation introduced by
QUEST_STATUS_COMPLETE is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
312
}
313
314
// TODO: Move here quest comlpletion checks
315
// TODO: Check mutiply condition quests
316
/*
317
function qst_check_completion(&$user, &$planet, )
318
{
319
}
320
*/
321