Passed
Branch main (f9aaf7)
by Jonathan
14:43
created

TokenService   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 29
rs 10
c 0
b 0
f 0
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A generateRandomToken() 0 21 3
1
<?php
2
3
/**
4
 * webtrees-lib: MyArtJaub library for webtrees
5
 *
6
 * @package MyArtJaub\Webtrees
7
 * @subpackage AdminTasks
8
 * @author Jonathan Jaubart <[email protected]>
9
 * @copyright Copyright (c) 2021, Jonathan Jaubart
10
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3
11
 */
12
13
declare(strict_types=1);
14
15
namespace MyArtJaub\Webtrees\Module\AdminTasks\Services;
16
17
/**
18
 * Service for generating random tokens
19
 *
20
 */
21
class TokenService
22
{
23
    /**
24
     * Returns a random-ish generated token of a given size
25
     *
26
     * @param int $length Length of the token, default to 32
27
     * @return string Random token
28
     */
29
    public function generateRandomToken(int $length = 32): string
30
    {
31
        $chars = str_split('abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
32
        $len_chars = count($chars);
0 ignored issues
show
Bug introduced by
It seems like $chars can also be of type true; however, parameter $value of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

32
        $len_chars = count(/** @scrutinizer ignore-type */ $chars);
Loading history...
33
        $token = '';
34
35
        for ($i = 0; $i < $length; $i++) {
36
            $token .= $chars[mt_rand(0, $len_chars - 1)];
37
        }
38
39
        # Number of 32 char chunks
40
        $chunks = ceil(strlen($token) / 32);
41
        $md5token = '';
42
43
        # Run each chunk through md5
44
        for ($i = 1; $i <= $chunks; $i++) {
45
            $md5token .= md5(substr($token, $i * 32 - 32, 32));
46
        }
47
48
        # Trim the token to the required length
49
        return substr($md5token, 0, $length);
50
    }
51
}
52