Completed
Push — master ( 3542cf...29eead )
by Paweł
09:45
created

RandomnessGenerator::generateStringOfLength()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Component\Resource\Generator;
13
14
/**
15
 * @author Jan Góralski <[email protected]>
16
 */
17
final class RandomnessGenerator implements RandomnessGeneratorInterface
18
{
19
    /**
20
     * @var string
21
     */
22
    private $uriSafeAlphabet;
23
24
    /**
25
     * @var string
26
     */
27
    private $digits;
28
29
    public function __construct()
30
    {
31
        $this->digits = implode(range(0, 9));
32
33
        $this->uriSafeAlphabet =
34
            implode(range(0, 9))
35
            .implode(range('a', 'z'))
36
            .implode(range('A', 'Z'))
37
            .implode(['-', '_', '~', '.'])
38
        ;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function generateUriSafeString($length)
45
    {
46
        return $this->generateStringOfLength($length, $this->uriSafeAlphabet);
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function generateNumeric($length)
53
    {
54
        return $this->generateStringOfLength($length, $this->digits);
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function generateInt($min, $max)
61
    {
62
        return random_int($min, $max);
63
    }
64
65
    /**
66
     * @param int $length
67
     * @param string $alphabet
68
     *
69
     * @return string
70
     */
71
    private function generateStringOfLength($length, $alphabet)
72
    {
73
        $alphabetMaxIndex = strlen($alphabet) - 1;
74
        $randomString = '';
75
76
        for ($i = 0; $i < $length; ++$i) {
77
            $index = random_int(0, $alphabetMaxIndex);
78
            $randomString .= $alphabet[$index];
79
        }
80
81
        return $randomString;
82
    }
83
}
84