Completed
Pull Request — master (#4)
by Risan Bagja
02:18 queued 51s
created

NonceGenerator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 0
dl 0
loc 40
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A generate() 0 12 2
A base64EncodedRandomBytes() 0 4 1
A extractAlphaNumericFromBase64EncodedString() 0 4 1
1
<?php
2
3
namespace Risan\OAuth1\Request;
4
5
class NonceGenerator implements NonceGeneratorInterface
6
{
7
    /**
8
     * {@inheritDoc}
9
     */
10
    public function generate($length = 32)
11
    {
12
        $nonce = '';
13
14
        while (($currentNonceLength = strlen($nonce)) < $length) {
15
            $size = $length - $currentNonceLength;
16
            $randomString = $this->base64EncodedRandomBytes($size);
17
            $nonce .= substr($this->extractAlphaNumericFromBase64EncodedString($randomString), 0, $size);
18
        }
19
20
        return $nonce;
21
    }
22
23
    /**
24
     * Get cryptographically secure base64 encoded random bytes.
25
     *
26
     * @param  int $length
27
     * @return string
28
     */
29
    public function base64EncodedRandomBytes($length)
30
    {
31
        return base64_encode(random_bytes($length));
32
    }
33
34
    /**
35
     * Extract the alphanumeric characters from base64 encoded string.
36
     *
37
     * @param  string $string
38
     * @return string
39
     */
40
    public function extractAlphaNumericFromBase64EncodedString($string)
41
    {
42
        return str_replace(['/', '+', '='], '', $string);
43
    }
44
}
45