Random.php 1.0 KB

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