|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Alish\LaravelOtp\Util; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Arr; |
|
6
|
|
|
|
|
7
|
|
|
class Random |
|
8
|
|
|
{ |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* supported types: alpha, alphanumeric, numeric |
|
12
|
|
|
* @var string |
|
13
|
|
|
*/ |
|
14
|
|
|
protected string $type = 'alphanumeric'; |
|
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
protected int $length = 6; |
|
17
|
|
|
|
|
18
|
|
|
protected string $numerics = '0123456789'; |
|
19
|
|
|
|
|
20
|
|
|
protected string $alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
|
21
|
|
|
|
|
22
|
|
|
protected string $specials = "!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"; |
|
23
|
|
|
|
|
24
|
|
|
protected ?string $custom = null; |
|
25
|
|
|
|
|
26
|
|
|
public function __construct(array $config = []) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->type = Arr::get($config, 'type', $this->type); |
|
29
|
|
|
$this->length = Arr::get($config, 'length', $this->length); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function custom(string $custom): self |
|
33
|
|
|
{ |
|
34
|
|
|
$this->custom = $custom; |
|
35
|
|
|
return $this; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function type(string $type): self |
|
39
|
|
|
{ |
|
40
|
|
|
$this->type = $type; |
|
41
|
|
|
return $this; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function length(int $length): self |
|
45
|
|
|
{ |
|
46
|
|
|
$this->length = $length; |
|
47
|
|
|
return $this; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function generate(): string |
|
51
|
|
|
{ |
|
52
|
|
|
$random = ''; |
|
53
|
|
|
|
|
54
|
|
|
for ($i = 0; $i < $this->length; $i++) { |
|
55
|
|
|
$random .= $this->getRandomCharacter(); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return $random; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
public function characters(): array |
|
62
|
|
|
{ |
|
63
|
|
|
if (!is_null($this->custom)) { |
|
64
|
|
|
return str_split($this->custom); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
switch ($this->type) { |
|
68
|
|
|
case 'numeric': |
|
69
|
|
|
$characters = $this->numerics; |
|
70
|
|
|
break; |
|
71
|
|
|
case 'alpha': |
|
72
|
|
|
$characters = $this->alpha; |
|
73
|
|
|
break; |
|
74
|
|
|
case 'strong': |
|
75
|
|
|
$characters = $this->numerics . $this->alpha . $this->specials; |
|
76
|
|
|
break; |
|
77
|
|
|
case 'alphanumeric': |
|
78
|
|
|
default: |
|
79
|
|
|
$characters = $this->numerics . $this->alpha; |
|
80
|
|
|
break; |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
return str_split($characters); |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
public function getRandomCharacter(): string |
|
87
|
|
|
{ |
|
88
|
|
|
$characters = $this->characters(); |
|
89
|
|
|
return $characters[array_rand($characters)]; |
|
90
|
|
|
} |
|
91
|
|
|
|
|
92
|
|
|
} |
|
93
|
|
|
|