Completed
Push — master ( 9fe868...76e584 )
by Dimas
91:10 queued 74:51
created

coupon::pdo_required()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 3
nop 0
dl 0
loc 12
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
namespace User;
4
5
class coupon extends user
6
{
7
  public $coupon = null;
8
9
  public function __construct($user = 'root', $pass = '', $db = 'darkit', $host = 'localhost', $charset = 'utf8mb4')
10
  {
11
    parent::__construct($user, $pass, $db, $host, $charset);
12
  }
13
14
  public function set_pdo(\DB\pdo $pdo)
15
  {
16
    $this->pdo = $pdo;
0 ignored issues
show
Bug introduced by
The property pdo is declared private in User\user and cannot be accessed from this context.
Loading history...
17
  }
18
19
  public function pdo_required()
20
  {
21
    if (!$this->pdo_instance() || empty($this->pdo_instance())) {
22
      if ('any' == \MVC\helper::HeaderAccept() && !\MVC\helper::cors()) {
0 ignored issues
show
Bug introduced by
Are you sure the usage of MVC\helper::HeaderAccept() targeting MVC\helper::HeaderAccept() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

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

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

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

Loading history...
introduced by
The condition 'any' == MVC\helper::HeaderAccept() is always false.
Loading history...
23
        throw new \MVC\Exception('PDO Required', 1);
24
      } else {
25
        \JSON\json::json(['error' => true, 'message' => '\DB\pdo instance is required', 'title' => __CLASS__]);
26
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
27
      }
28
    }
29
30
    return $this;
31
  }
32
33
  public function create(string $coupon, int $limit)
34
  {
35
    $this->pdo_required();
36
    $check = $this->pdo_instance()->select('coupon')->where(['code' => $coupon])->row_array();
37
    $result = ['error' => true];
38
    if (isset($check['code'])) {
39
      $result['message'] = "Account `$coupon` already exists";
40
    } else {
41
      $insert = $this->pdo_instance()->insert_not_exists('coupon', ['code' => $coupon, 'limit' => $limit])->exec();
42
      $result = array_replace($result, $insert);
43
      if (!$result['error']) {
44
        $result['message'] = 'Coupon account created';
45
        $result['data'] = $this->pdo_instance()->select('coupon')->where(['code' => $coupon])->row_array();
46
      }
47
    }
48
    $result['title'] = 'Coupon Creation';
49
50
    return $result;
51
  }
52
53
  public function coupon_login(string $coupon)
54
  {
55
    $this->pdo_required();
56
    $result = ['title' => 'Coupon Login', 'error' => true];
57
    $login = $this->pdo_instance()
58
      ->select('coupon')
59
      ->where(['code' => $coupon])
60
      ->row_array();
61
    \Session\session::set_session('coupon', $login);
62
    $result = array_replace($result, $login);
63
    if (!isset($login['limit'])) {
64
      $result['error'] = true;
65
      $result['message'] = 'Coupon not registered';
66
    } else {
67
      $limit = $login['limit'] - $login['success'];
68
      if ($limit < 1) {
69
        $result['error'] = true;
70
        $result['message'] = 'Coupon was reached limit';
71
        //$this->logout();
72
      } else {
73
        $result['error'] = false;
74
        $result['message'] = 'Coupon login successfully';
75
        /**
76
         * Update token.
77
         */
78
        $uid = session_id();
79
        $uid .= '_' . $this->gen_token(strlen($uid));
80
        \Session\session::set_session('coupon_token', $uid);
81
        $this->pdo_instance()
82
          ->update(
83
            'coupon',
84
            ['token' => $uid],
85
            ['code' => $this->coupon_data('code')]
86
          )->exec();
87
      }
88
    }
89
    //$result = array_replace($result, $this->coupon());
90
91
    return $result;
92
  }
93
94
  /**
95
   * Coupon login check.
96
   *
97
   * @return boolean
98
   */
99
  public function is_login(bool $token = true)
100
  {
101
    if ($token) {
102
      return \Session\session::has('coupon_token', false) && !empty($this->coupon_data('code'));
103
    }
104
105
    return !empty($this->coupon_data('code'));
106
  }
107
108
  public function logout()
109
  {
110
    \Session\session::unses([
111
      'coupon_token', 'coupon_admin', 'coupon', 'im3', 'telkomsel', 'msisdn', 'tokenid',
112
    ]);
113
    \Cookie\helper::destroy();
114
  }
115
116
  public function is_admin()
117
  {
118
    return \Cookie\helper::has(str_rot13('coupon_admin'), false);
119
  }
120
121
  public function admin_required()
122
  {
123
    if (!$this->is_admin()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->is_admin() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
124
      exit(\JSON\json::json(['error' => true, 'message' => 'admin required']));
0 ignored issues
show
Bug introduced by
Are you sure the usage of JSON\json::json(array('e...' => 'admin required')) targeting JSON\json::json() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

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

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

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

Loading history...
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
125
    }
126
  }
127
128
  public function set_admin($data, int $expire = 15, string $cookie_path)
129
  {
130
    \Cookie\helper::mins(str_rot13('coupon_admin'), $data, $expire, $cookie_path, $_SERVER['HTTP_HOST']);
131
  }
132
133
  /**
134
   * Is localhost ?
135
   */
136
  public function is_local()
137
  {
138
    if (defined('LOCAL')) {
139
      return LOCAL;
140
    }
141
    return \MVC\helper::isLocal();
142
  }
143
144
  /**
145
   * Validate coupon token with current session zone divisor.
146
   *
147
   * @param callable $callback return callback(true|false, $result)
148
   *
149
   * @return boolean|mixed
150
   */
151
  public function coupon_validate(callable $callback = null)
152
  {
153
    $this->pdo_required();
154
    $result = ['title' => 'Coupon validate', 'error' => true];
155
    if ($this->is_admin() || $this->is_local()) {
156
      $result['session'] = \Session\session::all();
157
    }
158
    if ($this->is_login()) {
159
      $result['status'] = 'login';
160
      $coupon = $this->coupon();
161
      $dbtoken = null;
162
      if (isset($coupon['token'])) {
163
        $dbtoken = $coupon['token'];
164
      }
165
166
      $result['data'] = $coupon;
167
      $result['token']['db'] = $dbtoken;
168
      $result['token']['session'] = \Session\session::get('coupon_token');
169
170
      if (\Session\session::get('coupon_token') == $dbtoken) {
171
        $limit = $this->coupon_limit();
172
        $result['limit'] = $limit;
173
        if ($limit > 0) {
174
          $result['error'] = false;
175
        } else {
176
          $result['message'] = 'Token limit was reached';
177
        }
178
      } else {
179
        $result['message'] = 'Token coupon doesnt match';
180
      }
181
    } else {
182
      $result['message'] = 'Coupon login required';
183
    }
184
    if (is_callable($callback)) {
185
      return call_user_func($callback, (false === $result['error']), $result);
186
    }
187
188
    return false === $result['error']; //check if valid (true)
189
  }
190
191
  /**
192
   * Add Success 1 to database.
193
   *
194
   * @param string $coupon_code
195
   *
196
   * @return void
197
   */
198
  public function add_success(string $coupon_code)
199
  {
200
    $this->pdo_required();
201
    $this->pdo_instance()->query("UPDATE `coupon` SET `success`= `success`+1 WHERE `code` = '{$coupon_code}'")->exec();
202
  }
203
204
  public function add_log(string $msisdn, string $coupon_code)
205
  {
206
    $this->pdo_required();
207
    $regex = '/^0|^\+62/s';
208
    $msisdn = preg_replace($regex, '62', trim($msisdn));
209
    $this->pdo_instance()->insert('coupon_log', ['msisdn' => $msisdn, 'coupon' => $coupon_code])->exec();
210
  }
211
212
  /**
213
   * Get current coupon limit value.
214
   *
215
   * @return int
216
   */
217
  public function coupon_limit()
218
  {
219
    $coupon = $this->coupon();
220
    $ret = 0;
221
    if (isset($coupon['limit'], $coupon['success'])) {
222
      $ret = $coupon['limit'] - $coupon['success'];
223
    }
224
    if ($ret < 1) {
225
      $this->logout();
226
    }
227
228
    return $ret;
229
  }
230
231
  /**
232
   * Get current coupon datas.
233
   *
234
   * @return array
235
   */
236
  public function coupon()
237
  {
238
    $this->pdo_required();
239
    if (!$this->is_login()) {
240
      return null;
241
    }
242
    $ret = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
243
    try {
244
      $ret = $this->pdo_instance()->select('coupon')->where(['code' => $this->coupon_data('code')])->row_array();
245
      \Session\session::set_session('coupon', $ret);
246
    } catch (\Throwable $th) {
247
      //ev($this->pdo_instance());
248
      //throw $th;
249
    }
250
251
    return $ret;
252
  }
253
254
  public function coupon_data(string $key)
255
  {
256
    if (isset($_SESSION['coupon'][$key])) {
257
      return $_SESSION['coupon'][$key];
258
    }
259
  }
260
261
  public function redirect(string $path)
262
  {
263
    //\MVC\router::safe_redirect($path);
264
    if (!headers_sent()) {
265
      header('Location: ' . $path);
266
    } else {
267
      echo 'Your access was blocked. please visit <a href="' . $path . '">Here ' . md5($path) . '</a>';
268
    }
269
    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
270
  }
271
272
  /**
273
   * Generate token.
274
   *
275
   * @param int $length
276
   *
277
   * @return string
278
   */
279
  public function gen_token(int $length = 10)
280
  {
281
    $token = '';
282
    $codeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
283
    $codeAlphabet .= 'abcdefghijklmnopqrstuvwxyz';
284
    $codeAlphabet .= '0123456789';
285
    $max = strlen($codeAlphabet); // edited
286
287
    for ($i = 0; $i < $length; ++$i) {
288
      $token .= $codeAlphabet[random_int(0, $max - 1)];
289
    }
290
291
    return $token;
292
  }
293
294
  public function e($data)
295
  {
296
    exit(\JSON\json::json($data));
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
Bug introduced by
Are you sure the usage of JSON\json::json($data) targeting JSON\json::json() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

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

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

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

Loading history...
297
  }
298
}
299