Passed
Branch master (372b2a)
by Filipe
01:32
created

UriSafeTokenGenerator   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 6
c 0
b 0
f 0
dl 0
loc 32
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A generateToken() 0 13 1
1
<?php
2
3
/**
4
 * This file is part of web-stack
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Slick\WebStack\Domain\Security\Csrf\TokenGenerator;
13
14
use Slick\WebStack\Domain\Security\Csrf\TokenGeneratorInterface;
15
use InvalidArgumentException;
16
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...
17
18
/**
19
 * UriSafeTokenGenerator
20
 *
21
 * @package Slick\WebStack\Domain\Security\Csrf\TokenGenerator
22
 */
23
final class UriSafeTokenGenerator implements TokenGeneratorInterface
24
{
25
26
    /**
27
     * Generates URI-safe CSRF tokens.
28
     *
29
     * @param int $entropy The amount of entropy collected for each token (in bits)
30
     */
31
    public function __construct(private readonly int $entropy = 256)
32
    {
33
        if ($this->entropy <= 7) {
34
            throw new InvalidArgumentException('CSRF entropy should be greater than 7.');
35
        }
36
    }
37
38
    /**
39
     * @inheritDoc
40
     * @throws RandomException
41
     */
42
    public function generateToken(): string
43
    {
44
        // Generate a URI safe base64 encoded string that does not contain "+",
45
        // "/" or "=" which need to be URL encoded and make URLs unnecessarily
46
        // longer.
47
        /**
48
         * @template max
49
         * @phpstan-var int<1, max> $length
50
         */
51
        $length = intdiv($this->entropy, 8);
52
        $bytes = random_bytes($length);
53
54
        return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
55
    }
56
}
57