Completed
Push — master ( 75955e...d5bb65 )
by Freek
01:22
created

Policy::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 0
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Csp\Policies;
4
5
use Spatie\Csp\Directive;
6
use Illuminate\Http\Request;
7
use Spatie\Csp\Exceptions\InvalidDirective;
8
use Symfony\Component\HttpFoundation\Response;
9
10
abstract class Policy
11
{
12
    protected $directives = [];
13
14
    protected $reportOnly = false;
15
16
    abstract public function configure();
17
18
    /**
19
     * @param string $directive
20
     * @param string|array $values
21
     *
22
     * @return \Spatie\Csp\Policies\Policy
23
     *
24
     * @throws \Spatie\Csp\Exceptions\InvalidDirective
25
     */
26
    public function addDirective(string $directive, $values): self
27
    {
28
        $this->guardAgainstInvalidDirectives($directive);
29
30
        foreach (array_wrap($values) as $value) {
31
            $sanitizedValue = $this->sanitizeValue($value);
32
33
            if (! in_array($sanitizedValue, $this->directives[$directive] ?? [])) {
34
                $this->directives[$directive][] = $sanitizedValue;
35
            }
36
        }
37
38
        return $this;
39
    }
40
41
    public function reportOnly(): self
42
    {
43
        $this->reportOnly = true;
44
45
        return $this;
46
    }
47
48
    public function enforce(): self
49
    {
50
        $this->reportOnly = false;
51
52
        return $this;
53
    }
54
55
    public function reportTo(string $uri): self
56
    {
57
        $this->directives['report-uri'] = [$uri];
58
59
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
60
        $reportToContents = json_encode([
61
            'url' => $uri,
62
            'group-name' => class_basename(static::class),
63
            'max-age' => 60 * 60 * 24 * 7 * 30,
64
        ]);
65
66
        $this->directives['report-to'] = [$reportToContents];
67
        */
68
69
        return $this;
70
    }
71
72
    public function shouldBeApplied(Request $request, Response $response): bool
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $response is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
73
    {
74
        return config('csp.enabled');
75
    }
76
77
    public function addNonceForDirective(string $directive): self
78
    {
79
        return $this->addDirective($directive, "'nonce-".app('csp-nonce')."'");
80
    }
81
82
    public function applyTo(Response $response)
83
    {
84
        $this->configure();
85
86
        $headerName = $this->reportOnly
87
            ? 'Content-Security-Policy-Report-Only'
88
            : 'Content-Security-Policy';
89
90
        if ($response->headers->has($headerName)) {
91
            return;
92
        }
93
94
        $response->headers->set($headerName, (string) $this);
95
    }
96
97
    public function __toString()
98
    {
99
        return collect($this->directives)
100
            ->map(function (array $values, string $directive) {
101
                $valueString = implode(' ', $values);
102
103
                return "{$directive} {$valueString}";
104
            })
105
            ->implode(';');
106
    }
107
108
    protected function guardAgainstInvalidDirectives(string $directive)
109
    {
110
        if (! Directive::isValid($directive)) {
111
            throw InvalidDirective::notSupported($directive);
112
        }
113
    }
114
115
    protected function sanitizeValue(string $value): string
116
    {
117
        $specialDirectiveValues = [
118
            'none',
119
            'report-sample',
120
            'self',
121
            'strict-dynamic',
122
            'unsafe-eval',
123
            'unsafe-inline',
124
        ];
125
126
        if (in_array($value, $specialDirectiveValues)) {
127
            return "'{$value}'";
128
        }
129
130
        return $value;
131
    }
132
}
133