Skip to content

Commit 8ab8488

Browse files
authored
Configure headers in response setup
1 parent b244945 commit 8ab8488

File tree

1 file changed

+7
-14
lines changed

1 file changed

+7
-14
lines changed

src/Bridges/HttpDI/HttpExtension.php

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -71,13 +71,9 @@ public function loadConfiguration()
7171
}
7272

7373

74-
public function afterCompile(Nette\PhpGenerator\ClassType $class)
74+
public function beforeCompile()
7575
{
76-
if ($this->cliMode) {
77-
return;
78-
}
79-
80-
$initialize = $class->getMethod('initialize');
76+
$builder = $this->getContainerBuilder();
8177
$config = $this->getConfig();
8278
$headers = array_map('strval', $config['headers']);
8379

@@ -91,16 +87,14 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
9187
$headers['X-Frame-Options'] = $frames;
9288
}
9389

94-
$code = [];
9590
foreach (['csp', 'cspReportOnly'] as $key) {
9691
if (empty($config[$key])) {
9792
continue;
9893
}
9994
$value = self::buildPolicy($config[$key]);
10095
if (strpos($value, "'nonce'")) {
101-
$code[0] = '$cspNonce = base64_encode(random_bytes(16));';
10296
$value = Nette\DI\ContainerBuilder::literal(
103-
'str_replace(?, ? . $cspNonce, ?)',
97+
'str_replace(?, ? . (isset($cspNonce) \? $cspNonce : $cspNonce = base64_encode(random_bytes(16))), ?)',
10498
["'nonce", "'nonce-", $value]
10599
);
106100
}
@@ -111,16 +105,15 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
111105
$headers['Feature-Policy'] = self::buildPolicy($config['featurePolicy']);
112106
}
113107

114-
$code[] = Helpers::formatArgs('$response = $this->getService(?);', [$this->prefix('response')]);
115108
foreach ($headers as $key => $value) {
116109
if ($value !== '') {
117-
$code[] = Helpers::formatArgs('$response->setHeader(?, ?);', [$key, $value]);
110+
$builder->getDefinition($this->prefix('response'))
111+
->addSetup('?->setHeader(?, ?);', ['@self', $key, $value]);
118112
}
119113
}
120114

121-
$code[] = Helpers::formatArgs('$response->setCookie(...?);', [['nette-samesite', '1', 0, '/', null, null, true, 'Strict']]);
122-
123-
$initialize->addBody("(function () {\n\t" . implode("\n\t", $code) . "\n})();");
115+
$builder->getDefinition($this->prefix('response'))
116+
->addSetup('?->setCookie(...?)', ['@self', ['nette-samesite', '1', 0, '/', null, null, true, 'Strict']]);
124117
}
125118

126119

0 commit comments

Comments
 (0)