|
1
|
|
|
<?php namespace Comodojo\Zip\Foundation\Utils; |
|
2
|
|
|
|
|
3
|
|
|
use \InvalidArgumentException; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* @package Comodojo Foundation |
|
7
|
|
|
* @author Marco Giovinazzi <[email protected]> |
|
8
|
|
|
* @license MIT |
|
9
|
|
|
* |
|
10
|
|
|
* LICENSE: |
|
11
|
|
|
* |
|
12
|
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|
13
|
|
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|
14
|
|
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|
15
|
|
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|
16
|
|
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|
17
|
|
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
|
18
|
|
|
* THE SOFTWARE. |
|
19
|
|
|
*/ |
|
20
|
|
|
|
|
21
|
|
|
class UniqueId { |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Generate a custom uid starting from a prefix |
|
25
|
|
|
* |
|
26
|
|
|
* The result uid format will be $string-[random] |
|
27
|
|
|
* |
|
28
|
|
|
* @param string $prefix |
|
29
|
|
|
* @param int $length |
|
30
|
|
|
* @return string |
|
31
|
|
|
*/ |
|
32
|
|
|
public static function generateCustom($prefix, $length=128) { |
|
33
|
|
|
|
|
34
|
|
|
if ( $length <= (strlen($prefix)+1) ) { |
|
35
|
|
|
throw new InvalidArgumentException("Uid length cannot be smaller than prefix length +1"); |
|
36
|
|
|
|
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
return "$prefix-".self::generate($length-(strlen($prefix)+1)); |
|
40
|
|
|
|
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Generate an uid |
|
45
|
|
|
* |
|
46
|
|
|
* @param int $length |
|
47
|
|
|
* @return string |
|
48
|
|
|
*/ |
|
49
|
|
|
public static function generate($length=128) { |
|
50
|
|
|
|
|
51
|
|
|
if ($length < 32) { |
|
52
|
|
|
|
|
53
|
|
|
return substr(self::getUid(), 0, $length); |
|
54
|
|
|
|
|
55
|
|
|
} else if ($length == 32) { |
|
56
|
|
|
|
|
57
|
|
|
return self::getUid(); |
|
58
|
|
|
|
|
59
|
|
|
} else { |
|
60
|
|
|
|
|
61
|
|
|
$numString = (int)($length/32) + 1; |
|
62
|
|
|
$randNum = ""; |
|
63
|
|
|
for ($i = 0; $i < $numString; $i++) $randNum .= self::getUid(); |
|
64
|
|
|
|
|
65
|
|
|
return substr($randNum, 0, $length); |
|
66
|
|
|
|
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* Generate an uid (128 bit / 32 char random) |
|
73
|
|
|
* |
|
74
|
|
|
* @param int $length |
|
75
|
|
|
* @return string |
|
76
|
|
|
*/ |
|
77
|
|
|
protected static function getUid() { |
|
78
|
|
|
|
|
79
|
|
|
return md5(uniqid(rand(), true), 0); |
|
80
|
|
|
|
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
} |