Passed
Push — master ( 572343...b02c13 )
by Jean-Christophe
01:22
created

NonceGenerator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 2
rs 10
cc 1
nc 1
nop 1
1
<?php
2
namespace Ubiquity\security\csp;
3
4
use Ubiquity\utils\http\URequest;
5
6
class NonceGenerator {
7
8
	private array $nonces = [];
9
10
	private $onNonce;
11
12
	public function __construct(?callable $onNonce) {
13
		$this->onNonce = $onNonce;
14
	}
15
16
	protected function _generateNonce(string $name, ?int $value = null): string {
17
		$bytes = \random_bytes((int) ($value ?? 32));
18
		$nonce = \base64_encode($bytes);
19
		if (isset($this->onNonce) && ! URequest::isAjax()) {
20
			$onNonce = $this->onNonce;
21
			$onNonce($name, $nonce);
22
		}
23
		return $nonce;
24
	}
25
26
	/**
27
	 * Returns a new or an existing nonce value.
28
	 *
29
	 * @param string $name
30
	 * @param int $size
31
	 * @return string
32
	 */
33
	public function getNonce(string $name, int $size = 32): string {
34
		return $this->nonces[$name] ??= self::_generateNonce($name, $size);
0 ignored issues
show
Bug Best Practice introduced by
The method Ubiquity\security\csp\No...rator::_generateNonce() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

34
		return $this->nonces[$name] ??= self::/** @scrutinizer ignore-call */ _generateNonce($name, $size);
Loading history...
35
	}
36
37
	/**
38
	 *
39
	 * @param string $name
40
	 * @return bool
41
	 */
42
	public function hasNonce(string $name): bool {
43
		return isset($this->nonces[$name]);
44
	}
45
46
	/**
47
	 *
48
	 * @return string
49
	 */
50
	public function __toString() {
51
		return \count($this->nonces);
52
	}
53
}
54