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
8declare(strict_types=1);
9
10namespace Nette\Utils;
11
12use Nette;
13
14
15/**
16 * Secure random string generator.
17 */
18final class Random
19{
20	use Nette\StaticClass;
21
22	/**
23	 * Generates a random string of given length from characters specified in second argument.
24	 * Supports intervals, such as `0-9` or `A-Z`.
25	 */
26	public static function generate(int $length = 10, string $charlist = '0-9a-z'): string
27	{
28		$charlist = preg_replace_callback(
29			'#.-.#',
30			fn(array $m): string => implode('', range($m[0][0], $m[0][2])),
31			$charlist,
32		);
33		$charlist = count_chars($charlist, mode: 3);
34		$chLen = strlen($charlist);
35
36		if ($length < 1) {
37			throw new Nette\InvalidArgumentException('Length must be greater than zero.');
38		} elseif ($chLen < 2) {
39			throw new Nette\InvalidArgumentException('Character list must contain at least two chars.');
40		}
41
42		$res = '';
43		for ($i = 0; $i < $length; $i++) {
44			$res .= $charlist[random_int(0, $chLen - 1)];
45		}
46
47		return $res;
48	}
49}
50