Passed
Pull Request — master (#8)
by Alexander
08:23
created

TokenGenerator::getIntegerToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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 3
    public function __construct(int $length = 6)
17
    {
18 3
        $this->length = $length;
19 3
    }
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 1
    public function getIntegerToken(): int
36
    {
37 1
        return mt_rand(1 * pow(10, $this->length - 1), str_repeat(9, $this->length));
38
    }
39
40 2
    protected function getDefaultEnvironmentToken(): ?string
41
    {
42 2
        $token = getenv('TOKEN_GENERATOR_DEFAULT');
43
44 2
        if (!is_string($token) || mb_strlen($token) < $this->length) {
45 2
            return null;
46
        }
47
48 1
        return mb_substr($token, 0, $this->length);
49
    }
50
}
51