Passed
Push — master ( 62bba1...82ae54 )
by Jean-Christophe
01:08
created

NonceGenerator::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 2
rs 10
cc 1
nc 1
nop 0
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
	public function getNonce(string $name,int $size=32) {
27
		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

27
		return $this->nonces[$name] ??= self::/** @scrutinizer ignore-call */ _generateNonce($name, $size);
Loading history...
28
	}
29
	
30
	public function __toString(){
31
		return \count($this->nonces);
32
	}
33
}
34
35