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

Random   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 18
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
dl 0
loc 18
rs 10
c 1
b 0
f 0
ccs 5
cts 5
cp 1
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A string() 0 8 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