1010namespace Nette \Bridges \HttpDI ;
1111
1212use Nette ;
13- use Nette \PhpGenerator \Helpers ;
1413use Nette \Schema \Expect ;
1514
1615
@@ -76,13 +75,13 @@ public function loadConfiguration()
7675 }
7776
7877
79- public function afterCompile ( Nette \ PhpGenerator \ ClassType $ class )
78+ public function beforeCompile ( )
8079 {
8180 if ($ this ->cliMode ) {
8281 return ;
8382 }
8483
85- $ initialize = $ class -> getMethod ( ' initialize ' );
84+ $ builder = $ this -> getContainerBuilder ( );
8685 $ config = $ this ->config ;
8786 $ headers = array_map ('strval ' , $ config ->headers );
8887
@@ -96,16 +95,14 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
9695 $ headers ['X-Frame-Options ' ] = $ frames ;
9796 }
9897
99- $ code = [];
10098 foreach (['csp ' , 'cspReportOnly ' ] as $ key ) {
10199 if (empty ($ config ->$ key )) {
102100 continue ;
103101 }
104102 $ value = self ::buildPolicy ($ config ->$ key );
105103 if (strpos ($ value , "'nonce' " )) {
106- $ code [0 ] = '$cspNonce = base64_encode(random_bytes(16)); ' ;
107104 $ value = Nette \DI \ContainerBuilder::literal (
108- 'str_replace(?, ? . $cspNonce, ?) ' ,
105+ 'str_replace(?, ? . (isset( $cspNonce) \? $cspNonce : $cspNonce = base64_encode(random_bytes(16))) , ?) ' ,
109106 ["'nonce " , "'nonce- " , $ value ]
110107 );
111108 }
@@ -116,16 +113,16 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
116113 $ headers ['Feature-Policy ' ] = self ::buildPolicy ($ config ->featurePolicy );
117114 }
118115
119- $ code [] = Helpers::formatArgs ('$response = $this->getService(?); ' , [$ this ->prefix ('response ' )]);
116+ $ response = $ builder ->getDefinition ($ this ->prefix ('response ' ));
117+ assert ($ response instanceof Nette \DI \Definitions \ServiceDefinition);
118+
120119 foreach ($ headers as $ key => $ value ) {
121120 if ($ value !== '' ) {
122- $ code [] = Helpers:: formatArgs ( ' $response ->setHeader(?, ?); ' , [$ key , $ value ]);
121+ $ response -> addSetup ( ' ? ->setHeader(?, ?); ' , [' @self ' , $ key , $ value ]);
123122 }
124123 }
125124
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})(); " );
125+ $ response ->addSetup ('?->setCookie(...?) ' , ['@self ' , ['nette-samesite ' , '1 ' , 0 , '/ ' , null , null , true , 'Strict ' ]]);
129126 }
130127
131128
0 commit comments