AlertProvider.php
11 months ago
ApiClient.php
11 months ago
DateTimeHelper.php
11 months ago
DateTimes.php
11 months ago
DateTimesImmutable.php
11 months ago
Debugger.php
11 months ago
DisplayHelper.php
11 months ago
EmailHelper.php
11 months ago
PostTypeHelper.php
11 months ago
Random.php
11 months ago
SecurityValidator.php
11 months ago
ShortcodeSubstitutor.php
11 months ago
TemplateProvider.php
11 months ago
functions.php
11 months ago
Random.php
57 lines
| 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 | |
| 8 | namespace FapiMember\Utils; |
| 9 | |
| 10 | use InvalidArgumentException; |
| 11 | |
| 12 | /** |
| 13 | * Secure random string generator. |
| 14 | */ |
| 15 | final class Random { |
| 16 | |
| 17 | |
| 18 | /** |
| 19 | * Generates a random string of given length from characters specified in second argument. |
| 20 | * Supports intervals, such as `0-9` or `A-Z`. |
| 21 | * |
| 22 | * @param int $length |
| 23 | * @param string $charlist |
| 24 | * @return string |
| 25 | */ |
| 26 | public static function generate( $length = 10, $charlist = '0-9a-z' ) { |
| 27 | $charlist = count_chars( |
| 28 | preg_replace_callback( |
| 29 | '#.-.#', |
| 30 | static function ( array $m ) { |
| 31 | return implode( '', range( $m[0][0], $m[0][2] ) ); |
| 32 | }, |
| 33 | $charlist |
| 34 | ), |
| 35 | 3 |
| 36 | ); |
| 37 | |
| 38 | $chLen = strlen( $charlist ); |
| 39 | |
| 40 | if ( $length < 1 ) { |
| 41 | throw new InvalidArgumentException( 'Length must be greater than zero.' ); |
| 42 | } |
| 43 | |
| 44 | if ( $chLen < 2 ) { |
| 45 | throw new InvalidArgumentException( 'Character list must contain at least two chars.' ); |
| 46 | } |
| 47 | |
| 48 | $res = ''; |
| 49 | for ( $i = 0; $i < $length; $i++ ) { |
| 50 | $res .= $charlist[ random_int( 0, $chLen - 1 ) ]; |
| 51 | } |
| 52 | |
| 53 | return $res; |
| 54 | } |
| 55 | |
| 56 | } |
| 57 |