Issues (413)

app/Helpers/Helpers.php (11 issues)

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: sheldon
5
 * Date: 17-10-25
6
 * Time: 下午4:51.
7
 */
8
if (!function_exists('current_auth_user')) {
9
10
    /**
11
     * @param bool $throwException
12
     *
13
     * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
14
     *
15
     * @return \Yeelight\Models\Foundation\BaseUser
16
     */
17
    function current_auth_user($throwException = true)
18
    {
19
        $user = app('Dingo\Api\Auth\Auth')->user(false);
20
        $user = !empty($user) ? $user : \Auth::user();
21
        if (!$user || !($user instanceof \Yeelight\Models\Foundation\BaseUser)) {
22
            if ($throwException) {
23
                throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException('User Invalid Or Token Expired');
24
            }
25
        }
26
27
        return $user;
28
    }
29
}
30
31
if (!function_exists('auth_check')) {
32
33
    /**
34
     * @return bool
35
     */
36
    function auth_check()
37
    {
38
        return \Auth::check();
39
    }
40
}
41
42
if (!function_exists('current_full_url')) {
43
    function current_full_url($withQueryString = true)
44
    {
45
        $url = \Request::url();
46
        $query = $withQueryString ? (isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null) : null;
47
48
        if ($query) {
49
            $path = \Request::path();
50
            if (starts_with($query, $path.'&')) {
51
                $query = substr($query, strlen($path) + 1);
52
            } elseif (starts_with($query, $path)) {
53
                $query = substr($query, strlen($path));
54
            }
55
        }
56
57
        $url = $query ? $url.'?'.$query : $url;
58
59
        return $url;
60
    }
61
}
62
63
if (!function_exists('get_client_ip')) {
64
65
    /**
66
     * @return array|string
67
     */
68
    function get_client_ip()
69
    {
70
        $request = request();
71
        $clientIp = $request->header('X-Client-Ip');
72
        if (empty($clientIp)) {
73
            $clientIp = $request->getClientIp(true);
0 ignored issues
show
The call to Symfony\Component\HttpFo...\Request::getClientIp() has too many arguments starting with true. ( Ignorable by Annotation )

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

73
            /** @scrutinizer ignore-call */ 
74
            $clientIp = $request->getClientIp(true);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
74
        }
75
76
        return $clientIp;
77
    }
78
}
79
80
if (!function_exists('app_locale')) {
81
    function app_locale()
82
    {
83
        return \App::getLocale();
84
    }
85
}
86
87
if (!function_exists('app_timezone')) {
88
89
    /**
90
     * @return mixed
91
     */
92
    function app_timezone()
93
    {
94
        return \Config::get('app.timezone');
95
    }
96
}
97
98
if (!function_exists('jwt_token')) {
99
100
    /**
101
     * @return string|null
102
     */
103
    function jwt_token()
104
    {
105
        $jwt_token = \Session::get('jwt_token');
106
        if (is_jwt_token_valid_for_refresh($jwt_token, true)
107
            || (empty($jwt_token) && \Auth::check())
108
        ) {
109
            $refreshed_token = refresh_jwt_token();
110
            if (!empty($refreshed_token)) {
111
                $jwt_token = $refreshed_token;
112
            }
113
        }
114
115
        return $jwt_token;
116
    }
117
}
118
119
if (!function_exists('refresh_jwt_token')) {
120
121
    /**
122
     * @return string|null
123
     */
124
    function refresh_jwt_token()
125
    {
126
        $jwt_token = null;
127
        if (\Auth::check()) {
128
            $jwt_token = \JWTAuth::fromUser(current_auth_user());
129
            \Session::put('jwt_token', $jwt_token);
130
        }
131
132
        return $jwt_token;
133
    }
134
}
135
136
if (!function_exists('is_jwt_token_valid_for_refresh')) {
137
138
    /**
139
     * @param $token
140
     * @param bool $allowExpireRefresh
141
     *
142
     * @return bool
143
     */
144
    function is_jwt_token_valid_for_refresh($token, $allowExpireRefresh = false)
145
    {
146
        $is_jwt_token_valid_for_refresh = false;
147
148
        try {
149
            $payload = \JWTAuth::getPayload($token);
150
            $exp = $payload->get('exp');
151
            $nbf = $payload->get('nbf');
152
            if ($exp > 0 && $nbf > 0) {
153
                $nowTime = \Carbon\Carbon::now('UTC');
154
                $expireTime = \Carbon\Carbon::createFromTimestampUTC($exp);
155
                $validTime = \Carbon\Carbon::createFromTimestampUTC($nbf);
156
157
                // if now time is after valid time
158
                if ($nowTime->gt($validTime)) {
159
                    $minutesAfterValid = $nowTime->diffInMinutes($validTime);
160
                    $minutesBeforeExpire = $nowTime->diffInMinutes($expireTime);
0 ignored issues
show
The assignment to $minutesBeforeExpire is dead and can be removed.
Loading history...
161
                    $totalValidLength = $validTime->diffInMinutes($expireTime);
162
                    $halfAmountOfMinutes = floor($totalValidLength / 2);
163
                    if ($minutesAfterValid >= $halfAmountOfMinutes) {
164
                        $is_jwt_token_valid_for_refresh = true;
165
                    }
166
                }
167
            }
168
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
169
            if ($allowExpireRefresh) {
170
                $is_jwt_token_valid_for_refresh = true;
171
            }
172
        } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
173
        }
174
175
        return $is_jwt_token_valid_for_refresh;
176
    }
177
}
178
179
if (!function_exists('phone_parse')) {
180
181
    /**
182
     * @param string $phone_number
183
     * @param string $country_code An ISO 3166-1 two letter country code
184
     *
185
     * @return null|\libphonenumber\PhoneNumber
186
     */
187
    function phone_parse($phone_number, $country_code)
188
    {
189
        $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
190
191
        try {
192
            $phoneNumberProto = $phoneUtil->parseAndKeepRawInput($phone_number, $country_code);
193
194
            return $phoneNumberProto;
195
        } catch (\libphonenumber\NumberParseException $e) {
196
            return;
197
        }
198
    }
199
}
200
201
if (!function_exists('phone_model_from')) {
202
203
    /**
204
     * @param string $phone_number
205
     * @param string $country_code An ISO 3166-1 two letter country code
206
     *
207
     * @return \Yeelight\Models\Basic\PhoneNumberModel
208
     */
209
    function phone_model_from($phone_number, $country_code)
210
    {
211
        return new \Yeelight\Models\Basic\PhoneNumberModel($phone_number, $country_code);
212
    }
213
}
214
215
if (!function_exists('ip_to_country_iso_code')) {
216
    function ip_to_country_iso_code($ip = null, $default_iso_code = 'US')
217
    {
218
        if (empty($ip)) {
219
            $ip = get_client_ip();
220
        }
221
222
        $location = \GeoIP::getLocation($ip);
0 ignored issues
show
The type GeoIP 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...
223
224
        // check if NOT returned default
225
        if ($location['default'] === false && !empty($location['iso_code'])) {
226
            return $location['iso_code'];
227
        } elseif ($location['default'] === false && !empty($location['isoCode'])) {
228
            return $location['isoCode'];
229
        } else {
230
            return $default_iso_code;
231
        }
232
    }
233
}
234
235
if (!function_exists('collection_paginate')) {
236
237
    /**
238
     * @param \Illuminate\Support\Collection $collection
239
     * @param $perPage
240
     * @param string $pageName
241
     * @param null   $page
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $page is correct as it would always require null to be passed?
Loading history...
242
     *
243
     * @return \Illuminate\Pagination\LengthAwarePaginator
244
     */
245
    function collection_paginate(\Illuminate\Support\Collection $collection, $perPage, $pageName = 'page', $page = null)
246
    {
247
        $page = $page ?: \Illuminate\Pagination\Paginator::resolveCurrentPage($pageName);
248
249
        $results = $collection->forPage($page, $perPage);
250
251
        parse_str(request()->getQueryString(), $query);
252
        unset($query[$pageName]);
253
254
        return new \Illuminate\Pagination\LengthAwarePaginator($results, $collection->count(), $perPage, $page, [
255
                'pageName' => $pageName,
256
                'path'     => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
257
                'query'    => $query,
258
            ]
259
        );
260
    }
261
}
262
263
if (!function_exists('str_contains_ascii_only')) {
264
    function str_contains_ascii_only($string)
265
    {
266
        return preg_match('%^[ -~]+$%', $string, $m);
267
    }
268
}
269
270
if (!function_exists('in_arrayi')) {
271
    function in_arrayi($needle, $haystack)
272
    {
273
        return in_array(strtolower($needle), array_map('strtolower', $haystack));
274
    }
275
}
276
277
if (!function_exists('auth_user')) {
278
279
    /**
280
     * @param bool $throwException
281
     *
282
     * @return null|\Yeelight\Models\Foundation\BaseUser|\Yeelight\Models\Foundation\BaseUser
283
     */
284
    function auth_user($throwException = true)
285
    {
286
        return current_auth_user($throwException);
287
    }
288
}
289
290
if (!function_exists('yee_mix')) {
291
    function yee_mix($path, $manifestDirectory = '', $supportHot = true)
292
    {
293
        $path = mix($path, $manifestDirectory);
294
        if (!$supportHot) {
295
            $hotUrl = '//localhost:8080';
296
            if (starts_with($path, $hotUrl)) {
297
                $path = str_replace($hotUrl, '', $path);
298
            }
299
        }
300
301
        return $path;
302
    }
303
}
304
305
if (!function_exists('rest_client')) {
306
307
    /**
308
     * @param null $service_name
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $service_name is correct as it would always require null to be passed?
Loading history...
309
     * @param null $debug_mode
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $debug_mode is correct as it would always require null to be passed?
Loading history...
310
     *
311
     * @return \Yeelight\Services\Rest\RestClient
312
     */
313
    function rest_client($service_name = null, $debug_mode = null)
314
    {
315
        return new \Yeelight\Services\Rest\RestClient($service_name, $debug_mode);
316
    }
317
}
318
319
if (!function_exists('json_encode_safe')) {
320
    function json_encode_safe($value, $options = 0, $depth = 512)
321
    {
322
        $encoded = json_encode($value, $options, $depth);
323
        switch (json_last_error()) {
324
            case JSON_ERROR_NONE:
325
                return $encoded;
326
            case JSON_ERROR_DEPTH:
327
                throw new Exception('Maximum stack depth exceeded');
328
            case JSON_ERROR_STATE_MISMATCH:
329
                throw new Exception('Underflow or the modes mismatch');
330
            case JSON_ERROR_CTRL_CHAR:
331
                throw new Exception('Unexpected control character found');
332
            case JSON_ERROR_SYNTAX:
333
                throw new Exception('Syntax error, malformed JSON');
334
            case JSON_ERROR_UTF8:
335
                $clean = utf8ize($value);
336
337
                return json_encode_safe($clean, $options, $depth);
338
            default:
339
                throw new Exception('Unknown error');
340
        }
341
    }
342
}
343
344
if (!function_exists('json_decode_safe')) {
345
    function json_decode_safe($json, $assoc = false, $depth = 512)
346
    {
347
        $decoded = json_decode($json, $assoc, $depth);
348
        switch (json_last_error()) {
349
            case JSON_ERROR_NONE:
350
                return $decoded;
351
            case JSON_ERROR_DEPTH:
352
                throw new Exception('Maximum stack depth exceeded');
353
            case JSON_ERROR_STATE_MISMATCH:
354
                throw new Exception('Underflow or the modes mismatch');
355
            case JSON_ERROR_CTRL_CHAR:
356
                throw new Exception('Unexpected control character found');
357
            case JSON_ERROR_SYNTAX:
358
                throw new Exception('Syntax error, malformed JSON');
359
            case JSON_ERROR_UTF8:
360
                $clean = utf8ize($decoded);
361
362
                return json_decode_safe($clean, $assoc, $depth);
363
            default:
364
                throw new Exception('Unknown error');
365
        }
366
    }
367
}
368
369
if (!function_exists('utf8ize')) {
370
    function utf8ize($mixed)
371
    {
372
        if (is_array($mixed)) {
373
            foreach ($mixed as $key => $value) {
374
                $mixed[$key] = utf8ize($value);
375
            }
376
        } elseif (is_string($mixed)) {
377
            return utf8_encode($mixed);
378
        }
379
380
        return $mixed;
381
    }
382
}
383
384
if (!function_exists('read_exif_data_safe')) {
385
    function read_exif_data_safe($file, $sections_needed = null, $sub_arrays = null, $read_thumbnail = null)
0 ignored issues
show
The parameter $sub_arrays is not used and could be removed. ( Ignorable by Annotation )

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

385
    function read_exif_data_safe($file, $sections_needed = null, /** @scrutinizer ignore-unused */ $sub_arrays = null, $read_thumbnail = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $read_thumbnail is not used and could be removed. ( Ignorable by Annotation )

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

385
    function read_exif_data_safe($file, $sections_needed = null, $sub_arrays = null, /** @scrutinizer ignore-unused */ $read_thumbnail = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $sections_needed is not used and could be removed. ( Ignorable by Annotation )

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

385
    function read_exif_data_safe($file, /** @scrutinizer ignore-unused */ $sections_needed = null, $sub_arrays = null, $read_thumbnail = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
386
    {
387
        $data = null;
0 ignored issues
show
The assignment to $data is dead and can be removed.
Loading history...
388
389
        try {
390
            $data = read_exif_data($file);
391
        } catch (\Exception $e) {
392
            $data = null;
393
        }
394
395
        return $data;
396
    }
397
}
398