-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathShortId.php
52 lines (45 loc) · 1.47 KB
/
ShortId.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
namespace kotchuprik\short_id;
class ShortId
{
protected $alphabet;
public function __construct($alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
$this->alphabet = $alphabet;
}
public function encode($input, $neededLength = 0)
{
$output = '';
$base = strlen($this->alphabet);
if (is_numeric($neededLength)) {
$neededLength--;
if ($neededLength > 0) {
$input += pow($base, $neededLength);
}
}
for ($current = ($input != 0 ? floor(log($input, $base)) : 0); $current >= 0; $current--) {
$powed = pow($base, $current);
$floored = floor($input / $powed) % $base;
$output = $output . substr($this->alphabet, $floored, 1);
$input = $input - ($floored * $powed);
}
return $output;
}
public function decode($input, $neededLength = 0)
{
$output = 0;
$base = strlen($this->alphabet);
$length = strlen($input) - 1;
for ($current = $length; $current >= 0; $current--) {
$powed = pow($base, $length - $current);
$output = ($output + strpos($this->alphabet, substr($input, $current, 1)) * $powed);
}
if (is_numeric($neededLength)) {
$neededLength--;
if ($neededLength > 0) {
$output -= pow($base, $neededLength);
}
}
return $output;
}
}