TokenGenerator::getDefaultEnvironmentToken()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 3
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