Passed
Push — master ( d186bd...35d7a3 )
by Jean-Christophe
05:51
created

ContentSecurity::addHeaderToResponse()   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 0
1
<?php
2
namespace src\Ubiquity\security\csp;
3
4
use Ubiquity\utils\http\UResponse;
5
6
/**
7
 * Creates a Content Security Policy object.
8
 * Ubiquity\security\csp$ContentSecurity
9
 * This class is part of Ubiquity
10
 *
11
 * @author jc
12
 * @version 1.0.0
13
 *
14
 */
15
class ContentSecurity {
16
17
	const HEADER = 'Content-Security-Policy';
18
19
	const DEBUG_HEADER = 'Content-Security-Policy-Report-Only';
20
21
	private array $policies = [];
22
23
	private $header = self::HEADER;
24
25
	public function addPolicy(string $directive, array ...$values): self {
26
		$policies = $this->policies[$directive] ?? [];
27
		foreach ($values as $v) {
28
			if ($v === 'self' || $v === 'none') {
29
				$v = "'$v'";
30
			}
31
			$policies[$v] = true;
32
		}
33
		$this->policies[$directive] = $policies;
34
		return $this;
35
	}
36
37
	public function setDefaultSrc(array ...$policies) {
38
		return $this->addPolicy(CspDirectives::DEFAULT_SRC, ...$policies);
39
	}
40
41
	public function generate(): string {
42
		$strs = '';
43
		foreach ($this->policies as $directive => $policy) {
44
			$policies = \array_keys($policy);
45
			$strs .= $directive . ' ' . \implode(' ', $policies) . ';';
46
		}
47
		return $strs;
48
	}
49
50
	public function reportOnly(bool $reportOnly = true): self {
51
		$this->header = $reportOnly ? self::DEBUG_HEADER : self::HEADER;
52
		return $this;
53
	}
54
55
	public function addHeaderToResponse(): void {
56
		UResponse::header(self::HEADER, $this->generate());
57
	}
58
}
59
60