1 | <?php |
||
2 | |||
3 | namespace Mautic\CoreBundle\Helper\RandomHelper; |
||
4 | |||
5 | /** |
||
6 | * Class RandomHelper. |
||
7 | */ |
||
8 | final class RandomHelper implements RandomHelperInterface |
||
9 | { |
||
10 | /** |
||
11 | * Based on \Nette\Utils\Random. |
||
12 | * |
||
13 | * @param int $length |
||
14 | * @param string $charlist |
||
15 | * |
||
16 | * @return string |
||
17 | */ |
||
18 | public function generate($length = 10, $charlist = '0-9a-z') |
||
19 | { |
||
20 | $charlist = count_chars(preg_replace_callback('#.-.#', function (array $m) { |
||
21 | return implode('', range($m[0][0], $m[0][2])); |
||
22 | }, $charlist), 3); |
||
23 | $chLen = strlen($charlist); |
||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
24 | if ($length < 1) { |
||
25 | throw new \InvalidArgumentException('Length must be greater than zero.'); |
||
26 | } elseif ($chLen < 2) { |
||
27 | throw new \InvalidArgumentException('Character list must contain as least two chars.'); |
||
28 | } |
||
29 | $res = ''; |
||
30 | for ($i = 0; $i < $length; ++$i) { |
||
31 | $res .= $charlist[random_int(0, $chLen - 1)]; |
||
32 | } |
||
33 | |||
34 | return $res; |
||
35 | } |
||
36 | } |
||
37 |