-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPolicyFactory.php
More file actions
79 lines (68 loc) · 2.66 KB
/
PolicyFactory.php
File metadata and controls
79 lines (68 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
declare(strict_types=1);
namespace Flowpack\ContentSecurityPolicy\Factory;
use Flowpack\ContentSecurityPolicy\Exceptions\DirectivesNormalizerException;
use Flowpack\ContentSecurityPolicy\Exceptions\InvalidDirectiveException;
use Flowpack\ContentSecurityPolicy\Helpers\DirectivesNormalizer;
use Flowpack\ContentSecurityPolicy\Model\Nonce;
use Flowpack\ContentSecurityPolicy\Model\Policy;
use Neos\Flow\Annotations as Flow;
use Psr\Log\LoggerInterface;
/**
* @Flow\Scope("singleton")
*/
class PolicyFactory
{
/**
* @Flow\InjectConfiguration(path="throw-invalid-directive-exception")
*/
protected bool $throwInvalidDirectiveException;
/**
* @Flow\Inject
*/
protected LoggerInterface $logger;
/**
* @Flow\Inject
*
*/
/**
* @param array<string, array<int|string, mixed>|null> $defaultDirectives
* @param array<string, array<int|string, mixed>|null> $customDirectives
* @throws InvalidDirectiveException
* @throws DirectivesNormalizerException
*/
public function create(Nonce $nonce, array $defaultDirectives, array $customDirectives): Policy
{
$normalizedDefaultDirectives = DirectivesNormalizer::normalize($defaultDirectives);
$normalizedCustomDirectives = DirectivesNormalizer::normalize($customDirectives);
$resultDirectives = $normalizedDefaultDirectives;
foreach ($normalizedCustomDirectives as $key => $customDirective) {
if (array_key_exists($key, $resultDirectives)) {
$resultDirectives[$key] = array_merge($resultDirectives[$key], $customDirective);
} else {
// Custom directive is not present in default, still needs to be added.
$resultDirectives[$key] = $customDirective;
}
$resultDirectives[$key] = array_unique($resultDirectives[$key]);
}
$policy = new Policy();
$policy->setNonce($nonce);
foreach ($resultDirectives as $directive => $values) {
try {
$policy->addDirective($directive, $values);
} catch (InvalidDirectiveException $e
) {
if ($this->throwInvalidDirectiveException) {
// For development we want to make sure directives are configured correctly.
throw $e;
} else {
// In production we just log the error and continue. If a directive is invalid, we still
// want to apply the rest of the policy.
$this->logger->critical($e->getMessage());
continue;
}
}
}
return $policy;
}
}