Skip to content

Commit 1718bd2

Browse files
committed
Move response configuration from initialize method to response service
1 parent 9901e0f commit 1718bd2

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

src/Bridges/HttpDI/HttpExtension.php

+8-10
Original file line numberDiff line numberDiff line change
@@ -76,13 +76,13 @@ public function loadConfiguration()
7676
}
7777

7878

79-
public function afterCompile(Nette\PhpGenerator\ClassType $class)
79+
public function beforeCompile()
8080
{
8181
if ($this->cliMode) {
8282
return;
8383
}
8484

85-
$initialize = $class->getMethod('initialize');
85+
$builder = $this->getContainerBuilder();
8686
$config = $this->config;
8787
$headers = array_map('strval', $config->headers);
8888

@@ -96,16 +96,14 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
9696
$headers['X-Frame-Options'] = $frames;
9797
}
9898

99-
$code = [];
10099
foreach (['csp', 'cspReportOnly'] as $key) {
101100
if (empty($config->$key)) {
102101
continue;
103102
}
104103
$value = self::buildPolicy($config->$key);
105104
if (strpos($value, "'nonce'")) {
106-
$code[0] = '$cspNonce = base64_encode(random_bytes(16));';
107105
$value = Nette\DI\ContainerBuilder::literal(
108-
'str_replace(?, ? . $cspNonce, ?)',
106+
'str_replace(?, ? . (isset($cspNonce) \? $cspNonce : $cspNonce = base64_encode(random_bytes(16))), ?)',
109107
["'nonce", "'nonce-", $value]
110108
);
111109
}
@@ -116,16 +114,16 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
116114
$headers['Feature-Policy'] = self::buildPolicy($config->featurePolicy);
117115
}
118116

119-
$code[] = Helpers::formatArgs('$response = $this->getService(?);', [$this->prefix('response')]);
117+
$response = $builder->getDefinition($this->prefix('response'));
118+
assert($response instanceof Nette\DI\Definitions\ServiceDefinition);
119+
120120
foreach ($headers as $key => $value) {
121121
if ($value !== '') {
122-
$code[] = Helpers::formatArgs('$response->setHeader(?, ?);', [$key, $value]);
122+
$response->addSetup('?->setHeader(?, ?);', ['@self', $key, $value]);
123123
}
124124
}
125125

126-
$code[] = Helpers::formatArgs('$response->setCookie(...?);', [['nette-samesite', '1', 0, '/', null, null, true, 'Strict']]);
127-
128-
$initialize->addBody("(function () {\n\t" . implode("\n\t", $code) . "\n})();");
126+
$response->addSetup('?->setCookie(...?)', ['@self', ['nette-samesite', '1', 0, '/', null, null, true, 'Strict']]);
129127
}
130128

131129

0 commit comments

Comments
 (0)