PluginProbe
Packeta / 2.0.9
Packeta v2.0.9
2.3.2 2.3.1 trunk 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.3.0 1.3.1 1.3.2 1.4 1.4.1 1.4.2 1.4.3 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 All 56 releases
packeta / deps / nette / utils / src / Utils / Random.php

Random.php in Packeta 2.0.9, at deps/nette/utils/src/Utils/Random.php

39 lines 1.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * This file is part of the Nette Framework (https://nette.org)
5 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6 */
7 declare (strict_types=1);
8 namespace Packetery\Nette\Utils;
9
10 use Packetery\Nette;
11 /**
12 * Secure random string generator.
13 */
14 final class Random
15 {
16 use \Packetery\Nette\StaticClass;
17 /**
18 * Generates a random string of given length from characters specified in second argument.
19 * Supports intervals, such as `0-9` or `A-Z`.
20 */
21 public static function generate(int $length = 10, string $charlist = '0-9a-z') : string
22 {
23 $charlist = \count_chars(\preg_replace_callback('#.-.#', function (array $m) : string {
24 return \implode('', \range($m[0][0], $m[0][2]));
25 }, $charlist), 3);
26 $chLen = \strlen($charlist);
27 if ($length < 1) {
28 throw new \Packetery\Nette\InvalidArgumentException('Length must be greater than zero.');
29 } elseif ($chLen < 2) {
30 throw new \Packetery\Nette\InvalidArgumentException('Character list must contain at least two chars.');
31 }
32 $res = '';
33 for ($i = 0; $i < $length; $i++) {
34 $res .= $charlist[\random_int(0, $chLen - 1)];
35 }
36 return $res;
37 }
38 }
39