Random   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 22
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
A string() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Security;
6
7
use Yiisoft\Strings\StringHelper;
8
9
/**
10
 * Random allows generating random values.
11
 *
12
 * Currently it has a single method "string".
13
 * The following extras are available via PHP directly:
14
 *
15
 * - `random_bytes()` for bytes. Note that output may not be ASCII.
16
 * - `random_int()` for integers.
17
 */
18
final class Random
19
{
20
    /**
21
     * Generates a random string of specified length.
22
     * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
23
     *
24
     * @param int $length The length of the key in characters.
25
     *
26
     * @throws \Exception On failure.
27
     *
28
     * @return string The generated random key.
29
     */
30 5
    public static function string(int $length = 32): string
31
    {
32 5
        if ($length < 1) {
33 1
            throw new \InvalidArgumentException('First parameter ($length) must be greater than 0.');
34
        }
35
36
        // Optimization: we can generate a quarter fewer bits to completely cover the desired length in base64
37
        /** @psalm-suppress ArgumentTypeCoercion */
38 4
        $bytes = random_bytes((int) ceil($length * 0.75));
39 4
        return substr(StringHelper::base64UrlEncode($bytes), 0, $length);
40
    }
41
}
42