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