Issues (994)

src/Cookie/helper.php (6 issues)

1
<?php
2
3
namespace Cookie;
4
5
/**
6
 * Cookie helper.
7
 */
8
class helper
9
{
10
  public static $domain = '/';
11
  public static $secure = false;
12
13
  public static function secure(bool $secure)
14
  {
15
    self::$secure = $secure;
16
  }
17
18
  public static function domain(string $domain)
19
  {
20
    self::$domain = $domain;
21
  }
22
23
  /** This magic method is called everytime an inaccessible method is called
24
   * (either by visibility contrains or it doesn't exist)
25
   * Here we are simulating shared protected methods across "package" classes
26
   * This method is inherited by all child classes of Package.
27
   */
28
  public function __call($method, $args)
29
  {
30
    //class name
31
    $class = get_class($this);
32
33
    /* we check if a method exists, if not we throw an exception
34
     * similar to the default error
35
     */
36
    if (method_exists($this, $method)) {
37
      /** The method exists so now we want to know if the
38
       * caller is a child of our Package class. If not we throw an exception
39
       * Note: This is a kind of a dirty way of finding out who's
40
       * calling the method by using debug_backtrace and reflection.
41
       */
42
      $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
43
      if (isset($trace[2])) {
44
        $ref = new \ReflectionClass($trace[2]['class']);
45
        if ($ref->isSubclassOf(__CLASS__)) {
46
          return $this->$method($args);
47
        }
48
      }
49
      throw new \Exception("Call to private method $class::$method()");
50
    } else {
51
      throw new \Exception("Call to undefined method $class::$method()");
52
    }
53
  }
54
55
  /**
56
   * Set cookie helper.
57
   *
58
   * @param string    $name
59
   * @param mixed     $value
60
   * @param int|float|string $expire 1m/1h/1d/1y
61
   * @param string    $path
62
   * @param string    $domain   default $_SERVER['HTTP_HOST']
63
   * @param bool      $secure
64
   * @param bool      $httponly
65
   *
66
   * @return setcookie
0 ignored issues
show
The type Cookie\setcookie was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
67
   */
68
  public static function set(string $name, $value, $expire, string $path = '/', $domain = '', $secure = false, $httponly = false)
69
  {
70
    if (empty($domain)) {
71
      $domain = $_SERVER['HTTP_HOST'];
72
    }
73
    if (empty($path)) {
74
      $path = '/';
75
    }
76
77
    if (is_string($expire)) {
78
      if (endsWith($expire, "h")) {
79
        $expire = time() + (toNumber($expire) * 3600);
80
      } else if (endsWith($expire, "d")) {
81
        $expire = time() + (toNumber($expire) * 86400);
82
      } else if (endsWith($expire, "m")) {
83
        $expire = time() + (toNumber($expire) * 60);
84
      } else if (endsWith($expire, "y")) {
85
        $expire = time() + (toNumber($expire) * 31556926); // where 31556926 is total seconds for a year.
86
      }
87
    }
88
89
    try {
90
      //$value = gzdeflate(json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 9);
91
      //$value = base64_encode(json_encode($value));
92
      $value = aesEncrypt($value, md5($_SERVER['HTTP_HOST']));
93
    } catch (\MVC\Exception $E) {
94
      $value = $value;
95
    }
96
97
    if (!setcookie($name, $value, $expire, $path, $domain, $secure, $httponly)) {
0 ignored issues
show
It seems like $expire can also be of type double and string; however, parameter $expires_or_options of setcookie() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

97
    if (!setcookie($name, $value, /** @scrutinizer ignore-type */ $expire, $path, $domain, $secure, $httponly)) {
Loading history...
98
      return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type Cookie\setcookie.
Loading history...
99
    } else {
100
      return true;
0 ignored issues
show
Bug Best Practice introduced by
The expression return true returns the type true which is incompatible with the documented return type Cookie\setcookie.
Loading history...
101
    }
102
  }
103
104
  /**
105
   * Get Cookie By Name.
106
   *
107
   * @param string cookie value
0 ignored issues
show
The type Cookie\cookie was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
108
   * * if value is json, auto convert them into Array
109
   * @return null|string|array
110
   */
111
  public static function get(string $name, bool $AllowEmpty = true)
112
  {
113
    $ret = null;
114
    if (isset($_COOKIE[$name])) {
115
      $ret = $_COOKIE[$name];
116
    }
117
    if ($ret) {
118
      //$ret = json_decode(gzinflate($ret), true);
119
      //$ret = json_decode(base64_decode($ret), true);
120
      $ret = aesDecrypt($ret, md5($_SERVER['HTTP_HOST']));
121
    }
122
    if (!$AllowEmpty && empty($ret)) {
123
      $ret = null;
124
    }
125
126
    return $ret;
127
  }
128
129
  /**
130
   * Destroy all cookies except php session and spesific cookies name.
131
   *
132
   * @param array $except
133
   *
134
   * @return void
135
   */
136
  public static function destroy(array $except = [])
137
  {
138
    if (isset($_SERVER['HTTP_COOKIE'])) {
139
      $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
140
      $i = 0;
141
      foreach ($cookies as $cookie) {
142
        ++$i;
143
        $parts = explode('=', $cookie);
144
        $name = trim($parts[0]);
145
        //var_dump($name);
146
        if (preg_match('/PHPSESSID/s', $name) || in_array($name, $except)) {
147
          continue;
148
        }
149
        setcookie($name, '', time() - 1000);
150
        setcookie($name, '', time() - 1000, '/');
151
        setcookie($name, '', time() - 1000, self::get_current_path());
152
        if (20 == $i) {
153
          break;
154
        }
155
      }
156
    }
157
  }
158
159
  public static function all()
160
  {
161
    return $_COOKIE;
162
  }
163
164
  public static function get_current_url()
165
  {
166
    $pageURL = 'http';
167
    if (isset($_SERVER['HTTPS']) && 'on' == $_SERVER['HTTPS']) {
168
      $pageURL .= 's';
169
    }
170
    $pageURL .= '://';
171
    if ('80' != $_SERVER['SERVER_PORT']) {
172
      $pageURL .= $_SERVER['SERVER_NAME']
173
        . ':'
174
        . $_SERVER['SERVER_PORT']
175
        . $_SERVER['REQUEST_URI'];
176
    } else {
177
      $pageURL .= $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
178
    }
179
180
    return $pageURL;
181
  }
182
183
  public static function get_current_path()
184
  {
185
    $url_parts = \MVC\helper::parse_url2(self::get_current_url());
186
187
    return isset($url_parts['path']) ? $url_parts['path'] : '';
188
  }
189
190
  public static function reconstruct_url(string $url)
191
  {
192
    $url_parts = \MVC\helper::parse_url2($url);
193
    $constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . (isset($url_parts['path']) ? $url_parts['path'] : '');
194
195
    return $constructed_url;
196
  }
197
198
  /**
199
   * Set cookie by days.
200
   *
201
   * @see \Cookie\helper::set() automatically set expire time to day format
202
   */
203
  public static function day(string $name, $value = true, int $expire, string $path = '/', $domain = '', $secure = false, $httponly = false)
204
  {
205
    return self::set($name, $value, time() + 60 * 60 * 24 * $expire, $path, $domain, $secure, $httponly);
206
  }
207
208
  /**
209
   * Set cookie by minutes.
210
   *
211
   * @see \Cookie\helper::set() automatically set expire time to minutes format
212
   */
213
  public static function mins(string $name, $value = true, int $expire, string $path = '/', $domain = '', $secure = false, $httponly = false)
214
  {
215
    return self::set($name, $value, time() + (60 * $expire), $path, $domain, $secure, $httponly);
216
  }
217
218
  /**
219
   * Set cookie by hours.
220
   *
221
   * @see \Cookie\helper::set() automatically set expire time to hours format
222
   */
223
  public static function hours(string $name, $value = true, int $expire = 1, string $path = '/', $domain = '', $secure = false, $httponly = false)
224
  {
225
    return self::set($name, $value, time() + (60 * 60 * $expire), $path, $domain, $secure, $httponly);
226
  }
227
228
  /**
229
   * Check cookie exist.
230
   *
231
   * @param string $name
232
   * @param bool   $AllowEmpty if true, will return false if cookie value empty
233
   *
234
   * @return boolean|null
235
   *                      `true` indicated exists,
236
   *                      `null` indicated empty value,
237
   *                      `false` indicated not set
238
   */
239
  public static function has(string $name, bool $AllowEmpty = true)
240
  {
241
    $ret = false;
242
    if (isset($_COOKIE[$name])) {
243
      $ret = true;
244
    }
245
    if ((true !== $AllowEmpty) && empty($ret)) {
246
      $ret = null;
247
    }
248
249
    return $ret;
250
  }
251
252
  /**
253
   * one time function when cookie name empty.
254
   *
255
   * @param string   $cookie_name
256
   * @param string   $value
257
   * @param int      $minutes     minute to be expired
258
   * @param callable $callback
259
   *
260
   * @return void
261
   */
262
  public static function one(string $cookie_name, string $value, int $minutes, callable $callback)
263
  {
264
    if (!self::has($cookie_name)) {
265
      if (is_callable($callback)) {
266
        call_user_func($callback, $cookie_name, $minutes);
267
        self::mins($cookie_name, $value, $minutes);
268
      }
269
    }
270
  }
271
272
  /**
273
   * Delete cookie.
274
   *
275
   * @param string $name
276
   *
277
   * @return bool true | false | null
278
   *              * return true if success and exists
279
   *              * return false if cookie not exists
280
   *              * return null if $_COOKIE constant not exists
281
   */
282
  public static function del(string $name)
283
  {
284
    if (isset($_COOKIE[$name])) {
285
      unset($_COOKIE[$name]);
286
      setcookie($name, null, -1, '/');
287
288
      return true;
289
    } else {
290
      return false;
291
    }
292
293
    return null;
0 ignored issues
show
return null is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
294
  }
295
}
296