TokenGenerator::getRandomNumber()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.3222
c 0
b 0
f 0
cc 5
nc 4
nop 0
1
<?php
2
3
namespace BWC\Share\Security\TokenGenerator;
4
5
use Psr\Log\LoggerInterface;
6
7
class TokenGenerator implements TokenGeneratorInterface
8
{
9
    /** @var bool */
10
    private $useOpenSsl;
11
12
13
    public function __construct(LoggerInterface $logger = null)
14
    {
15
        $this->logger = $logger;
0 ignored issues
show
Bug introduced by
The property logger does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
16
17
        // determine whether to use OpenSSL
18
        if (defined('PHP_WINDOWS_VERSION_BUILD') && version_compare(PHP_VERSION, '5.3.4', '<')) {
19
            $this->useOpenSsl = false;
20
        } elseif (!function_exists('openssl_random_pseudo_bytes')) {
21
            if (null !== $this->logger) {
22
                $this->logger->notice('It is recommended that you enable the "openssl" extension for random number generation.');
23
            }
24
            $this->useOpenSsl = false;
25
        } else {
26
            $this->useOpenSsl = true;
27
        }
28
    }
29
30
    public function generateToken()
31
    {
32
        return base_convert(bin2hex($this->getRandomNumber()), 16, 36);
33
    }
34
35
    private function getRandomNumber()
36
    {
37
        $nbBytes = 32;
38
39
        // try OpenSSL
40
        if ($this->useOpenSsl) {
41
            $bytes = openssl_random_pseudo_bytes($nbBytes, $strong);
42
43
            if (false !== $bytes && true === $strong) {
44
                return $bytes;
45
            }
46
47
            if (null !== $this->logger) {
48
                $this->logger->info('OpenSSL did not produce a secure random number.');
49
            }
50
        }
51
52
        return hash('sha256', uniqid(mt_rand(), true), true);
53
    }
54
}