Generator::useSymbols()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Sludio\HelperBundle\Script\Utils;
4
5
class Generator
6
{
7
    const PASS_LOWERCASE = 'abcdefghijklmnopqrstuvwxyz';
8
    const PASS_UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
9
    const PASS_DIGITS = '0123456789';
10
    const PASS_SYMBOLS = '!@#$%^&*()_-=+;:.,?';
11
12
    const RAND_BASIC = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
13
    const RAND_EXTENDED = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_-=+;:,.?';
14
15
    private $sets = [];
16
17
    public function generate($length = 20)
18
    {
19
        $all = '';
20
        $password = '';
21
        foreach ($this->sets as $set) {
22
            $password .= $set[$this->tweak(str_split($set))];
23
            $all .= $set;
24
        }
25
        $all = str_split($all);
26
        for ($i = 0; $i < $length - \count($this->sets); $i++) {
27
            $password .= $all[$this->tweak($all)];
28
        }
29
30
        return str_shuffle($password);
31
    }
32
33
    public function tweak($array)
34
    {
35
        if (\function_exists('random_int')) {
36
            return random_int(0, \count($array) - 1);
37
        }
38
        if (\function_exists('mt_rand')) {
39
            return mt_rand(0, \count($array) - 1);
40
        }
41
42
        return array_rand($array);
43
    }
44
45
    public function useLower()
46
    {
47
        $this->sets['lower'] = self::PASS_LOWERCASE;
48
49
        return $this;
50
    }
51
52
    public function useUpper()
53
    {
54
        $this->sets['upper'] = self::PASS_UPPERCASE;
55
56
        return $this;
57
    }
58
59
    public function useDigits()
60
    {
61
        $this->sets['digits'] = self::PASS_DIGITS;
62
63
        return $this;
64
    }
65
66
    public function useSymbols()
67
    {
68
        $this->sets['symbols'] = self::PASS_SYMBOLS;
69
70
        return $this;
71
    }
72
73
    public static function getRandomString($length = 20, $chars = self::RAND_BASIC)
74
    {
75
        return substr(str_shuffle(str_repeat($chars, (int)ceil((int)($length / \strlen($chars))))), 1, $length);
76
    }
77
78
    public static function getUniqueId($length = 20)
79
    {
80
        try {
81
            return bin2hex(random_bytes($length));
82
        } catch (\Exception $exception) {
83
            return self::getRandomString($length);
84
        }
85
    }
86
}
87