@@ -71,13 +71,9 @@ public function loadConfiguration()
71
71
}
72
72
73
73
74
- public function afterCompile ( Nette \ PhpGenerator \ ClassType $ class )
74
+ public function beforeCompile ( )
75
75
{
76
- if ($ this ->cliMode ) {
77
- return ;
78
- }
79
-
80
- $ initialize = $ class ->getMethod ('initialize ' );
76
+ $ builder = $ this ->getContainerBuilder ();
81
77
$ config = $ this ->getConfig ();
82
78
$ headers = array_map ('strval ' , $ config ['headers ' ]);
83
79
@@ -91,16 +87,14 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
91
87
$ headers ['X-Frame-Options ' ] = $ frames ;
92
88
}
93
89
94
- $ code = [];
95
90
foreach (['csp ' , 'cspReportOnly ' ] as $ key ) {
96
91
if (empty ($ config [$ key ])) {
97
92
continue ;
98
93
}
99
94
$ value = self ::buildPolicy ($ config [$ key ]);
100
95
if (strpos ($ value , "'nonce' " )) {
101
- $ code [0 ] = '$cspNonce = base64_encode(random_bytes(16)); ' ;
102
96
$ value = Nette \DI \ContainerBuilder::literal (
103
- 'str_replace(?, ? . $cspNonce, ?) ' ,
97
+ 'str_replace(?, ? . (isset( $cspNonce) \? $cspNonce : $cspNonce = base64_encode(random_bytes(16))) , ?) ' ,
104
98
["'nonce " , "'nonce- " , $ value ]
105
99
);
106
100
}
@@ -111,16 +105,15 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
111
105
$ headers ['Feature-Policy ' ] = self ::buildPolicy ($ config ['featurePolicy ' ]);
112
106
}
113
107
114
- $ code [] = Helpers::formatArgs ('$response = $this->getService(?); ' , [$ this ->prefix ('response ' )]);
115
108
foreach ($ headers as $ key => $ value ) {
116
109
if ($ value !== '' ) {
117
- $ code [] = Helpers::formatArgs ('$response->setHeader(?, ?); ' , [$ key , $ value ]);
110
+ $ builder ->getDefinition ($ this ->prefix ('response ' ))
111
+ ->addSetup ('?->setHeader(?, ?); ' , ['@self ' , $ key , $ value ]);
118
112
}
119
113
}
120
114
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 ' ]]);
124
117
}
125
118
126
119
0 commit comments