Random::generateRandomBytes()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 15
rs 9.9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XMLSecurity\Utils;
6
7
use Random\RandomException;
0 ignored issues
show
Bug introduced by
The type Random\RandomException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use SimpleSAML\Assert\Assert;
9
use SimpleSAML\XMLSecurity\Exception\InvalidArgumentException;
10
use SimpleSAML\XMLSecurity\Exception\RuntimeException;
11
use ValueError;
12
13
use function random_bytes;
14
15
/**
16
 * A collection of utilities to generate cryptographically-secure random data.
17
 *
18
 * @package SimpleSAML\XMLSecurity\Utils
19
 */
20
class Random
21
{
22
    /**
23
     * Generate a given amount of cryptographically secure random bytes.
24
     *
25
     * @param positive-int $length The amount of bytes required.
26
     *
27
     * @return string A random string of $length length.
28
     *
29
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException
30
     *   If $length is not an integer greater than zero.
31
     * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException
32
     *   If no appropriate sources of cryptographically secure random generators are available.
33
     */
34
    public static function generateRandomBytes(int $length): string
35
    {
36
        Assert::positiveInteger(
37
            $length,
38
            'Invalid length received to generate random bytes.',
39
            InvalidArgumentException::class,
40
        );
41
42
        try {
43
            return random_bytes($length);
44
        } catch (ValueError) { // @phpstan-ignore-line
45
            throw new InvalidArgumentException('Invalid length received to generate random bytes.');
46
        } catch (RandomException) {
47
            throw new RuntimeException(
48
                'Cannot generate random bytes, no cryptographically secure random generator available.',
49
            );
50
        }
51
    }
52
}
53