RandomTokenGenerator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
ccs 3
cts 3
cp 1
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Majora\Component\OAuth\Generator;
4
5
/**
6
 * Generate a token.
7
 *
8
 * @see inspired from https://github.com/FriendsOfSymfony/FOSOAuthServerBundle/blob/master/Util/Random.php
9
 */
10
class RandomTokenGenerator
11
{
12
    /**
13
     * @var string
14
     */
15
    protected $secret;
16
17
    /**
18
     * Construct.
19
     *
20
     * @param string $secret
21
     */
22 4
    public function __construct($secret)
23
    {
24 4
        $this->secret = $secret;
25 4
    }
26
27
    /**
28
     * Generate a random token.
29
     *
30
     * @param string $intention contextual string
31
     *
32
     * @return string
33
     */
34 4
    public function generate($intention = 'm@J0raOaUth')
35
    {
36 4
        $bytes = false;
37 4
        if (function_exists('openssl_random_pseudo_bytes') && 0 !== stripos(PHP_OS, 'win')) {
38 4
            $bytes = openssl_random_pseudo_bytes(32, $strong);
39
40 4
            if (true !== $strong) {
41 2
                $bytes = false;
42 1
            }
43 2
        }
44
45
        // let's just hope we got a good seed
46 4
        if (false === $bytes) {
47 2
            $bytes = hash('sha512',
48 2
                sprintf('-[%s}\%s/{%s]-',
49 1
                    $intention,
50 2
                    uniqid(mt_rand(), true),
51 2
                    $this->secret
52 1
                ),
53 1
                true
54 1
            );
55 1
        }
56
57 4
        return str_pad(
58 4
            base_convert(bin2hex($bytes), 16, 36),
59 4
            50,
60 4
            rand(0, 9)
61 2
        );
62
    }
63
}
64