|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* GpsLab component. |
|
5
|
|
|
* |
|
6
|
|
|
* @author Peter Gribanov <[email protected]> |
|
7
|
|
|
* @copyright Copyright (c) 2011, Peter Gribanov |
|
8
|
|
|
* @license http://opensource.org/licenses/MIT |
|
9
|
|
|
*/ |
|
10
|
|
|
|
|
11
|
|
|
namespace GpsLab\Component\Base64UID\Generator; |
|
12
|
|
|
|
|
13
|
|
|
use GpsLab\Component\Base64UID\Exception\ArgumentTypeException; |
|
14
|
|
|
use GpsLab\Component\Base64UID\Exception\InvalidArgumentException; |
|
15
|
|
|
use GpsLab\Component\Base64UID\Exception\ZeroArgumentException; |
|
16
|
|
|
|
|
17
|
|
|
class RandomCharGenerator implements Generator |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* TODO use private const after drop PHP < 7.1. |
|
21
|
|
|
* |
|
22
|
|
|
* @var string |
|
23
|
|
|
*/ |
|
24
|
|
|
private static $DEFAULT_CHARSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-'; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @var int |
|
28
|
|
|
*/ |
|
29
|
|
|
private $uid_length; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @var string |
|
33
|
|
|
*/ |
|
34
|
|
|
private $charset; |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* @var int |
|
38
|
|
|
*/ |
|
39
|
|
|
private $charset_size; |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* @param int $uid_length |
|
43
|
|
|
* @param string $charset |
|
44
|
|
|
*/ |
|
45
|
10 |
|
public function __construct($uid_length = 10, $charset = null) |
|
46
|
|
|
{ |
|
47
|
|
|
// TODO move to method arguments after drop PHP < 7.1 |
|
48
|
10 |
|
if ($charset === null) { |
|
49
|
6 |
|
$charset = self::$DEFAULT_CHARSET; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
10 |
|
if (!is_int($uid_length)) { |
|
53
|
1 |
|
throw new ArgumentTypeException(sprintf('Length of UID should be integer, got "%s" instead.', gettype($uid_length))); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
9 |
|
if (!is_string($charset)) { |
|
57
|
1 |
|
throw new ArgumentTypeException(sprintf('Charset of UID should be a string, got "%s" instead.', gettype($charset))); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
8 |
|
if ($uid_length <= 0) { |
|
61
|
2 |
|
throw new ZeroArgumentException(sprintf('Length of UID should be grate then "0", got "%d" instead.', $uid_length)); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
6 |
|
if ($charset === '') { |
|
65
|
1 |
|
throw new InvalidArgumentException('Charset of UID should not be empty.'); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
5 |
|
$this->uid_length = $uid_length; |
|
69
|
5 |
|
$this->charset = $charset; |
|
70
|
5 |
|
$this->charset_size = strlen($charset); |
|
71
|
5 |
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* @return string |
|
75
|
|
|
*/ |
|
76
|
5 |
|
public function generate() |
|
77
|
|
|
{ |
|
78
|
5 |
|
$uid = ''; |
|
79
|
5 |
|
for ($i = 0; $i < $this->uid_length; ++$i) { |
|
80
|
5 |
|
$uid .= $this->charset[random_int(0, $this->charset_size - 1)]; |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
5 |
|
return $uid; |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|