wearesho-team /
yii-tokens
| 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
Loading history...
|
|||
| 37 | 3 | return null; |
|
| 38 | 3 | } |
|
| 39 | 2 | ||
| 40 | 1 | return mb_substr($token, 0, $this->length); |
|
| 41 | } |
||
| 42 | } |
||
| 43 |