Passed
Push — master ( 39eca3...00c19d )
by Alexander
07:20 queued 02:28
created

TokenGenerator::getDefaultEnvironmentToken()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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