Passed
Push — master ( bdfe7b...8f2aab )
by Alexander
01:12
created

Random::string()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
rs 10
c 1
b 0
f 0
ccs 5
cts 5
cp 1
crap 2
1
<?php declare(strict_types=1);
2
3
namespace Yiisoft\Security;
4
5
use Yiisoft\Strings\StringHelper;
6
7
/**
8
 * Random allows generating random values.
9
 *
10
 * Currently it has a single method "string".
11
 * The following extras are available via PHP directly:
12
 *
13
 * - `random_bytes()` for bytes. Note that output may not be ASCII.
14
 * - `random_int()` for integers.
15
 */
16
final class Random
17
{
18
    /**
19
     * Generates a random string of specified length.
20
     * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
21
     *
22
     * @param int $length the length of the key in characters
23
     * @return string the generated random key
24
     * @throws \Exception on failure.
25
     */
26 3
    public static function string(int $length = 32): string
27
    {
28 3
        if ($length < 1) {
29 1
            throw new \InvalidArgumentException('First parameter ($length) must be greater than 0');
30
        }
31
32 2
        $bytes = random_bytes($length);
33 2
        return substr(StringHelper::base64UrlEncode($bytes), 0, $length);
34
    }
35
}
36