|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bagsiz\EasyFunctions; |
|
4
|
|
|
|
|
5
|
|
|
use DateTime; |
|
6
|
|
|
|
|
7
|
|
|
class EasyFunction |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* Check a model's field against a random value. |
|
11
|
|
|
*/ |
|
12
|
|
|
public static function checkFieldForRandom($model, string $field, string $type = 'str', int $length = 8) |
|
13
|
|
|
{ |
|
14
|
|
|
if ($type == 'str') { |
|
15
|
|
|
$rnd = self::randomStr($length); |
|
16
|
|
|
} elseif ($type == 'int') { |
|
17
|
|
|
$rnd = self::randomInt($length); |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
$continue = true; |
|
21
|
|
|
while ($continue) { |
|
22
|
|
|
$check = $model->where($field, $rnd)->first(); |
|
|
|
|
|
|
23
|
|
|
|
|
24
|
|
|
if (! $check) { |
|
25
|
|
|
$continue = false; |
|
|
|
|
|
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
return $rnd; |
|
29
|
|
|
} |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
private static function randomStr($length = 16) |
|
33
|
|
|
{ |
|
34
|
|
|
$string = ''; |
|
35
|
|
|
|
|
36
|
|
|
while (($len = strlen($string)) < $length) { |
|
37
|
|
|
$size = $length - $len; |
|
38
|
|
|
|
|
39
|
|
|
$bytes = random_bytes($size); |
|
40
|
|
|
|
|
41
|
|
|
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
return $string; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
private static function randomInt($length = 4) |
|
48
|
|
|
{ |
|
49
|
|
|
$rand = ''; |
|
50
|
|
|
while (! (isset($rand[$length - 1]))) { |
|
51
|
|
|
$rand .= mt_rand(); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
return (int) substr($rand, 0, $length); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public static function decimalToTime($decimal) |
|
58
|
|
|
{ |
|
59
|
|
|
if (! $decimal) { |
|
60
|
|
|
return 'Empty data given.'; |
|
61
|
|
|
} |
|
62
|
|
|
if (strpos((string) $decimal, '.') !== false) { |
|
63
|
|
|
$timeArray = explode('.', $decimal); |
|
64
|
|
|
|
|
65
|
|
|
$zero = new DateTime('@0'); |
|
66
|
|
|
$offset = new DateTime("@$timeArray[0]"); |
|
67
|
|
|
$diff = $zero->diff($offset); |
|
68
|
|
|
|
|
69
|
|
|
$timeString = sprintf('%02d:%02d:%02d:%02d', $diff->days, $diff->h, $diff->i, $diff->s); |
|
70
|
|
|
|
|
71
|
|
|
if (isset($timeArray[1])) { |
|
72
|
|
|
if (strlen((string) $timeArray[1]) == 1) { |
|
73
|
|
|
$timeArray[1] = sprintf('%1s0', $timeArray[1]); |
|
74
|
|
|
|
|
75
|
|
|
return $timeString.'.'.$timeArray[1]; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
return $timeString.'.'.str_pad($timeArray[1], 2, '0', STR_PAD_LEFT); |
|
79
|
|
|
} else { |
|
80
|
|
|
return $timeString.'.00'; |
|
81
|
|
|
} |
|
82
|
|
|
} else { |
|
83
|
|
|
return 'Integer must contain "." for decimals'; |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|