Nonce::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * CSP
4
 *
5
 * @author     Kenji Suzuki <https://github.com/kenjis>
6
 * @license    MIT License
7
 * @copyright  2014 Kenji Suzuki
8
 * @link       https://github.com/kenjis/php-csp-nonce-source
9
 */
10
11
namespace Kenjis\Csp;
12
13
class Nonce
14
{
15
    const UNSUPPORTED_BROWSER_NONCE = 'dummy';
16
17
    /**
18
     * @var \Kenjis\Csp\Browser
19
     */
20
    private $browser;
21
22
    /**
23
     * @var string
24
     */
25
    private $nonce;
26
27
    /**
28
     * @param \Kenjis\Csp\Browser $browser
29
     */
30
    public function __construct(Browser $browser)
31
    {
32
        $this->browser = $browser;
33
    }
34
35
    private function generateNonce()
36
    {
37
        if (! $this->browser->supportNonceSource()) {
38
            $this->nonce = static::UNSUPPORTED_BROWSER_NONCE;
39
            return;
40
        }
41
42
        $length = 16;
43
        $usable = true;
44
        $bytes = openssl_random_pseudo_bytes($length, $usable);
45
        if ($usable === false) {
46
            // weak
47
            // @TODO do something?
48
        }
49
50
        $this->nonce = base64_encode($bytes);
51
    }
52
53
    /**
54
     * @return string
55
     */
56
    public function getNonce()
57
    {
58
        if ($this->nonce === null) {
59
            $this->generateNonce();
60
        }
61
62
        return $this->nonce;
63
    }
64
}
65