TokenGenerator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Wearesho\Yii\Services;
6
7
use Wearesho\Yii\Interfaces\TokenGeneratorInterface;
8
9
class TokenGenerator implements TokenGeneratorInterface
10
{
11
    protected int $length;
12
13
    public function __construct(int $length = 6)
14
    {
15
        $this->length = $length;
16 5
    }
17
18 5
    public function getToken(): string
19 5
    {
20
        $environmentToken = $this->getDefaultEnvironmentToken();
21 2
        if (!empty($environmentToken)) {
22
            return $environmentToken;
23 2
        }
24 2
25 1
        $numbers = range(0, 9);
26
27
        return implode('', array_map(function () use (&$numbers) {
28 2
            return array_rand($numbers);
29
        }, range(1, $this->length)));
30 2
    }
31 2
32 2
    protected function getDefaultEnvironmentToken(): ?string
33
    {
34
        $token = getenv('TOKEN_GENERATOR_DEFAULT');
35 3
36
        if (!is_string($token) || mb_strlen($token) < $this->length) {
0 ignored issues
show
introduced by
The condition is_string($token) is always true.
Loading history...
37 3
            return null;
38 3
        }
39 2
40 1
        return mb_substr($token, 0, $this->length);
41
    }
42
}
43