Completed
Push — master ( 06cc78...f70c47 )
by PROSPER
01:59
created

TransRef::getHashedToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Laravel Paystack package.
5
 *
6
 * (c) Prosper Otemuyiwa <[email protected]>
7
 *
8
 * Source http://stackoverflow.com/a/13733588/179104
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Unicodeveloper\Paystack;
15
16
class TransRef {
17
18
    public static function getPool( $type = 'alnum')
19
    {
20
        switch ( $type ) {
21
            case 'alnum':
22
                $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
23
                break;
24
            case 'alpha':
25
                $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
26
                break;
27
            case 'hexdec':
28
                $pool = '0123456789abcdef';
29
                break;
30
            case 'numeric':
31
                $pool = '0123456789';
32
                break;
33
            case 'nozero':
34
                $pool = '123456789';
35
                break;
36
            case 'distinct':
37
                $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
38
                break;
39
            default:
40
                $pool = (string) $type;
41
                break;
42
        }
43
44
        return $pool;
45
    }
46
47
48
    public static function secure_crypt($min, $max) {
49
        $range = $max - $min;
50
51
        if ($range < 0) {
52
            return $min; // not so random...
53
        }
54
55
        $log    = log($range, 2);
56
        $bytes  = (int) ($log / 8) + 1; // length in bytes
57
        $bits   = (int) $log + 1; // length in bits
58
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
59
        do {
60
            $rnd = hexdec( bin2hex( openssl_random_pseudo_bytes( $bytes ) ) );
61
            $rnd = $rnd & $filter; // discard irrelevant bits
62
        } while ($rnd >= $range);
63
64
        return $min + $rnd;
65
    }
66
67
    public static function getHashedToken($length = 25)
68
    {
69
        $token = "";
70
        $max   = strlen(static::getPool());
71
        for ($i = 0; $i < $length; $i++) {
72
            $token .= static::getPool()[static::secure_crypt(0, $max)];
73
        }
74
75
        return $token;
76
    }
77
78
}
79