Passed
Branch master (449dcd)
by refat
03:50
created

UsersController::validatorPasses()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 5
nop 2
dl 0
loc 14
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controllers\Admin;
4
5
use System\Controller as Controller;
6
use RandomLib\Factory as Factory;
7
8
class UsersController extends Controller
9
{
10
  public function index()
11
  {
12
    $users = $this->load->model('User')->users();
13
    $usersformatted = $this->formatUsers($users);
14
    $countries = $this->countries('all', 'name');
15
16
    $context = [
17
      'users' => $usersformatted,
18
      'countries' => $countries,
19
    ];
20
    return $this->view->render('admin/pages/users/users', $context);
21
  }
22
23
  public function row()
24
  {
25
    $id = userId();
26
    $model = $this->load->model('User');
27
    $user = $model->user($id);
28
29
    $user->new = $this->isUserNew($user->registration);
30
    $user->registration = $this->changeFormatDate($user->registration);
31
    $user->last_login = $this->changeFormatDate($user->last_login);
32
    $user->last_logout = $this->changeFormatDate($user->last_logout);
33
    $user->birthday = $this->changeFormatDate($user->birthday, ['Y-m-d', 'd M Y']);
34
    $user->country_icon = $this->countries($user->country);
35
36
    $countries = $this->countries('all', 'name');
37
    $countries_options = implode(',', $countries);
38
39
    $context = [
40
      'user' => $user,
41
      'countries_options' => $countries_options,
42
    ];
43
    return $this->view->render('admin/pages/users/user', $context);
44
  }
45
46
  public function formatUsers($users)
47
  {
48
    $users_for_list = [];
49
50
    foreach ($users as $user) {
51
      $user->new = $this->isUserNew($user->registration);
52
      $user->country_icon = $this->countries($user->country);
53
      $user->registration = $this->changeFormatDate($user->registration);
54
      $user->last_login = $this->changeFormatDate($user->last_login);
55
56
      $users_for_list[] = $user;
57
    }
58
    return $users_for_list;
59
  }
60
61
  public function filter()
62
  {
63
    $msg = null;
64
    $gets = $this->request->gets();
65
66
    if (empty($gets)) {
67
      $users = $this->load->model('User')->users();
68
69
      $usersformatted = $this->formatUsers($users);
70
      return json_encode($usersformatted);
71
    }
72
73
    $gender = $gets['gender'] ?? null;
74
    $zip = $gets['zip'] ?? null;
75
    $country = $gets['country'] ?? null;
76
    $registration_from = $gets['registration_from'] ?? null;
77
    $registration_to = $gets['registration_to'] ?? null;
78
    $active = $gets['active'] ?? null;
79
    $pending = $gets['pending'] ?? null;
80
    $inactive = $gets['inactive'] ?? null;
81
    $online = $gets['online'] ?? null;
82
    $offline = $gets['offline'] ?? null;
83
84
    $sql = '';
85
    $wheres = [];
86
87
    if ($active && $active == '1') {
88
      $sql .= 'status = ? AND ';
89
      array_push($wheres, '2');
90
    }
91
    if ($pending && $pending == '1') {
92
      $sql .= 'status = ? AND ';
93
      array_push($wheres, '1');
94
    }
95
    if ($inactive && $inactive == '1') {
96
      $sql .= 'status = ? AND ';
97
      array_push($wheres, '0');
98
    }
99
100
    $count_status = substr_count($sql, 'status = ?');
101
102
    if ($count_status > 1) {
103
      $sql = str_replace('status = ? AND', 'status = ? OR', $sql);
104
      $sql = rtrim($sql, 'OR ');
105
      $sql = "( $sql )";
106
      $sql .= ' AND ';
107
    }
108
109
    if ($online && $online == '1') {
110
      $sql .= 'is_login = ? AND ';
111
      array_push($wheres, '1');
112
    }
113
    if ($offline && $offline == '1') {
114
      $sql .= 'is_login = ? AND ';
115
      array_push($wheres, '0');
116
    }
117
118
    $count_is_login = substr_count($sql, 'is_login = ?');
119
120
    if ($count_is_login > 1) {
121
      $sql = str_replace('is_login = ? AND', 'is_login = ? OR', $sql);
122
      $sql = rtrim($sql, 'OR ');
123
      $sql = "( $sql )";
124
      $sql .= ' AND ';
125
    }
126
127
    if ($gender) {
128
      $sql .= 'gender = ? AND ';
129
      array_push($wheres, $gender);
130
    }
131
    if ($zip) {
132
      $sql .= 'zip = ? AND ';
133
      array_push($wheres, $zip);
134
    }
135
    if ($country) {
136
      $sql .= 'country = ? AND ';
137
      array_push($wheres, $country);
138
    }
139
140
    if ($registration_from) {
141
      $registration_from = date("Y-m-d", strtotime($registration_from));
142
143
      if (!$registration_to) {
144
        $sql .= 'registration >= ? AND ';
145
        array_push($wheres, $registration_from);
146
      } else {
147
        $registration_to = date("Y-m-d", strtotime($registration_to));
148
149
        $sql .= 'registration BETWEEN ? AND ? AND ';
150
        array_push($wheres, $registration_from);
151
        array_push($wheres, $registration_to);
152
      }
153
    }
154
155
    if ($sql == '') {
156
      $users = $this->load->model('User')->users();
157
158
      $usersformatted = $this->formatUsers($users);
159
160
      return json_encode($usersformatted);
161
    }
162
163
    $sql = substr($sql, 0, -4);
164
165
    $users = $this->load->model('User')->filter($sql, $wheres);
166
167
    if (!$users) {
168
      $msg = 'no users';
169
      return json_encode($msg);
170
    }
171
172
    $users_for_list = [];
173
174
    foreach ($users as $user) {
175
      $user->new = $this->isUserNew($user->registration);
176
      $user->country_icon = $this->countries($user->country);
177
      $user->registration = $this->changeFormatDate($user->registration);
178
      $user->last_login = $this->changeFormatDate($user->last_login);
179
180
      $users_for_list[] = $user;
181
    }
182
183
    $msg = $users_for_list;
184
    return json_encode($msg);
185
  }
186
187
  public function update()
188
  {
189
    $msg = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $msg is dead and can be removed.
Loading history...
190
    $id = userId();
191
192
    $posts = $this->request->posts();
193
    $name = array_keys($posts)[0];
194
    $allows = $this->file->call('config/admin/users/pages/update.php');
195
196
    $columns = $this->file->fileContent('config/admin/users/columns.json');
197
    $columns = json_decode($columns);
198
    $table = $columns->$name->table;
199
    $column = $columns->$name;
200
    $filters = $columns->$name->filters;
201
    $value = ($posts[$name] == '') ? null : isset($filters->date) ? date('Y-m-d', strtotime($posts[$name])) : $posts[$name];
202
    $user_id_table_name = $column->user_id_table_name;
203
204
    $methods = $this->updateMethods([
205
      'id' => $id,
206
      'name' => $name,
207
      'allows' => $allows,
208
      'table' => $table,
209
      'user_id_table_name' => $user_id_table_name,
210
      'value' => $value,
211
      'filters' => $filters,
212
    ]);
213
214
    $error = $this->checkForErrorsInUpdateMethods($methods);
215
    if ($error) {
216
      return json_encode($error);
217
    }
218
219
    $msg = $this->userUpdateMsg($name, $value, $filters);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $msg is correct as $this->userUpdateMsg($name, $value, $filters) targeting App\Controllers\Admin\Us...roller::userUpdateMsg() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
220
    return json_encode($msg);
221
  }
222
223
  private function checkForErrorsInUpdateMethods($methods)
224
  {
225
    $msg = null;
226
    foreach ($methods as $method => $options) {
227
      if (call_user_func_array(array($this, $method), $options[0]) == false) {
228
        if (array_keys($options[1])[0] === 'msg') {
229
          $msg = array_values($options[1]);
230
        } else {
231
          if (array_keys($options[1])[0] === 'error') {
232
            $msg['error'] = $this->validator->getErrors();
233
          } else {
234
            $msg[array_keys($options[1])[0]] = array_values($options[1]);
235
          }
236
        }
237
        return $msg;
238
      }
239
    }
240
    return false;
241
  }
242
243
  private function updateMethods($args)
244
  {
245
    extract($args);
246
    return [
247
      'isUserFound' => [
248
        [$id],
249
        ['msg' => 'reload'],
250
      ],
251
      'checkPostParameters' => [
252
        [$name, $allows],
253
        ['msg' => 'reload'],
254
      ],
255
      'isValueChanged' => [
256
        [$name, $table, $user_id_table_name, $id, $value],
257
        ['same' => $value ? strtolower($value) : ''],
258
      ],
259
      'validatorPasses' => [
260
        [$filters, $name],
261
        ['error' => ''],
262
      ],
263
      'updateUser' => [
264
        [$name, $value, $user_id_table_name, $id, $table],
265
        ['msg' => 'reload'],
266
      ],
267
    ];
268
  }
269
270
  private function checkPostParameters($name, $allows)
271
  {
272
    if (!in_array($name, $allows)) {
273
      return false;
274
    }
275
    return true;
276
  }
277
278
  private function userUpdateMsg($name, $value, $filters)
279
  {
280
    $msg = null;
281
282
    if ($name === 'country') {
283
      $msg['country'] = [
284
        $value => $this->countries($value),
285
      ];
286
    } else {
287
      $msg['text'] = isset($filters->date) ? $this->changeFormatDate($value, ['Y-m-d', 'd M Y']) : _e($value);
288
    }
289
    return $msg;
290
  }
291
292
  private function updateUser($name, $value, $user_id_table_name, $id, $table)
293
  {
294
    return $this->db->data($name, $value)->where($user_id_table_name . ' = ?', $id)->update($table);
295
  }
296
297
  private function isUserFound($id)
298
  {
299
    return $this->load->model('User')->get($id);
300
  }
301
302
  private function isValueChanged($name, $table, $user_id_table_name, $id, $value)
303
  {
304
    $current_value = $this->db->select($name)->from($table)->where($user_id_table_name . ' = ?', [$id])->fetch()->$name;
305
    if (($current_value === strtolower($value)) || ($value == null && $current_value == null)) {
306
      return false;
307
    }
308
    return true;
309
  }
310
311
  private function validatorPasses($filters, $name)
312
  {
313
    foreach ($filters as $func => $arg) {
314
      if (method_exists($this->validator, $func) == 1) {
315
        if (gettype($arg) === 'boolean') {
316
          if ($arg) {
317
            $this->validator->input($name)->$func();
318
          }
319
        } else {
320
          $this->validator->input($name)->$func($arg);
321
        }
322
      }
323
    }
324
    return $this->validator->passes();
325
  }
326
327
  public function new()
328
  {
329
    $countries = $this->countries('all', 'name');
330
    $context = [
331
      'countries' => $countries,
332
    ];
333
    return $this->view->render('admin/pages/users/new', $context);
334
  }
335
336
  public function add()
337
  {
338
    $msg = null;
339
    $posts = $this->request->posts();
340
    $names = array_keys($posts);
341
    $allows = $this->file->call('config/admin/users/pages/add.php');
342
343
    if (!array_equal($names, $allows)) {
344
      $msg = 'reload';
345
      return json_encode($msg);
346
    }
347
348
    $columns = $this->file->fileContent('config/admin/users/columns.json');
349
    $columns = json_decode($columns);
350
    $table = $this->load->model('User')->getTable();
351
352
    foreach ($names as $name) {
353
      $filters = $columns->$name->filters;
354
355
      foreach ($filters as $func => $arg) {
356
        if (method_exists($this->validator, $func) == 1) {
357
          if (gettype($arg) === 'boolean') {
358
            if ($arg) {
359
              $this->validator->input($name)->$func();
360
            }
361
          } else {
362
            $this->validator->input($name)->$func($arg);
363
          }
364
        }
365
      }
366
    }
367
368
    if ($this->validator->fails()) {
369
      $msg = $this->validator->getErrors();
370
      return json_encode($msg);
371
    }
372
373
    $factory = new Factory;
374
375
    $user_id = $factory->getMediumStrengthGenerator()->generateString(8, '0123456789');
376
    $code = $factory->getMediumStrengthGenerator()->generateString(20, '0123456789abcdefghijklmnopqrstuvwxyz');
377
    $username = $posts['username'];
378
    $fname = $posts['fname'];
379
    $lname = $posts['lname'];
380
    $gender = $posts['gender'];
381
    $birthday = date('Y-m-d', strtotime($posts['birthday']));
382
    $email = $posts['email'];
383
    $registration = $this->changeFormatDate(microtime(true), ['U.u', 'Y-m-d H:i:s']);
384
385
    $insertInUser = $this->db->data([
386
      'id' => $user_id,
387
      'code' => $code,
388
      'username' => $username,
389
      'fname' => $fname,
390
      'lname' => $lname,
391
      'gender' => $gender,
392
      'birthday' => $birthday,
393
      'email' => $email,
394
      'registration' => $registration,
395
    ])->insert($table);
396
397
    if (!$insertInUser) {
398
      $msg = 'reload';
399
      return json_encode($msg);
400
    }
401
402
    $country = $posts['country'] ? $posts['country'] : null;
403
    $state = $posts['state'] ? $posts['state'] : null;
404
    $city = $posts['city'] ? $posts['city'] : null;
405
    $zip = $posts['zip'] ? $posts['zip'] : null;
406
    $street = $posts['street'] ? $posts['street'] : null;
407
    $house_number = $posts['house_number'] ? $posts['house_number'] : null;
408
    $additional = $posts['additional'] ? $posts['additional'] : null;
409
410
    $insertInAddress = $this->db->data([
411
      'user_id' => $user_id,
412
      'country' => $country,
413
      'state' => $state,
414
      'city' => $city,
415
      'zip' => $zip,
416
      'street' => $street,
417
      'house_number' => $house_number,
418
      'additional' => $additional,
419
    ])->insert('address');
420
421
    $insertInActivity = $this->db->data([
422
      'user_id' => $user_id,
423
      'is_login' => 0,
424
    ])->insert('activity');
425
426
    if (!$insertInAddress || !$insertInActivity) {
427
      $msg = 'reload';
428
      return json_encode($msg);
429
    }
430
    $msg['success'] = $user_id;
431
    return json_encode($msg);
432
  }
433
434
  private function isUserNew($date)
435
  {
436
    if (!$date) {
437
      return;
438
    }
439
440
    $register_year = $this->changeFormatDate($date, ['Y-m-d H:i:s', 'Y']);
441
    $register_month = $this->changeFormatDate($date, ['Y-m-d H:i:s', 'm']);
442
    $register_day = $this->changeFormatDate($date, ['Y-m-d H:i:s', 'd']);
443
444
    $year = date('Y');
445
    $month = date('m');
446
    $day = date('d');
447
448
    $years = $year - $register_year;
449
450
    if ($years === 0) {
451
      $months = $month - $register_month;
452
453
      if ($months === 0) {
454
        $days = $day - $register_day;
455
456
        if ($days < 1) {
457
          return 1;
458
        }
459
      }
460
    }
461
    return 0;
462
  }
463
}
464