Completed
Push — master ( b10c64...511a60 )
by Freek
02:20
created

Profile::guardAgainstInvalidDirectives()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace Spatie\Csp\Profiles\Profile;
4
5
use Spatie\Csp\Directive;
6
use Spatie\Csp\Exceptions\InvalidDirective;
7
use Symfony\Component\HttpFoundation\Response;
8
9
abstract class Profile
10
{
11
    protected $directives = [];
12
13
    protected $reportOnly = false;
14
15
    public function addDirective(string $directive, string $value): self
16
    {
17
        $this->guardAgainstInvalidDirectives($directive);
18
19
        $this->directives[$directive][] = $value;
20
21
        return $this;
22
    }
23
24
    abstract public function registerDirectives();
25
26
    public function reportOnly(): self
27
    {
28
        $this->reportOnly = true;
29
30
        return $this;
31
    }
32
33
    public function enforce(): self
34
    {
35
        $this->reportOnly = false;
36
37
        return $this;
38
    }
39
40
    public function reportTo(string $uri): self
41
    {
42
        $this->directives['report-uri'] = $uri;
43
44
        $this->directives['report-to'] = json_encode([
45
           'url' => $uri,
46
           'group-name' => class_basename(static::class),
47
           'max-age => 60 * 60 * 24 * 7 * 30',
48
        ]);
49
50
        return $this;
51
    }
52
53
54
55
    public function applyTo(Response $response)
56
    {
57
        $this->registerDirectives();
58
59
        $headerName = $this->reportOnly
60
            ? 'Content-Security-Policy-Report-Only'
61
            : 'Content-Security-Policy';
62
63
        $response->headers->set($headerName, (string) $this);
64
    }
65
66
    protected function guardAgainstInvalidDirectives(string $directive)
67
    {
68
        if (! Directive::isValid($directive)) {
69
            throw InvalidDirective::notSupported($directive);
70
        }
71
    }
72
73
    public function __toString()
74
    {
75
        return collect($this->directives)
76
            ->map(function (array $values, string $directive) {
77
                $valueString = implode(' ', $values);
78
79
                return "{$directive} {$valueString}";
80
            })
81
            ->implode(';');
82
    }
83
}
84