1010namespace Nette \Bridges \HttpDI ;
1111
1212use Nette ;
13- use Nette \PhpGenerator \Helpers ;
1413
1514
1615/**
@@ -71,13 +70,13 @@ public function loadConfiguration()
7170 }
7271
7372
74- public function afterCompile ( Nette \ PhpGenerator \ ClassType $ class )
73+ public function beforeCompile ( )
7574 {
7675 if ($ this ->cliMode ) {
7776 return ;
7877 }
7978
80- $ initialize = $ class -> getMethod ( ' initialize ' );
79+ $ builder = $ this -> getContainerBuilder ( );
8180 $ config = $ this ->getConfig ();
8281 $ headers = array_map ('strval ' , $ config ['headers ' ]);
8382
@@ -91,16 +90,14 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
9190 $ headers ['X-Frame-Options ' ] = $ frames ;
9291 }
9392
94- $ code = [];
9593 foreach (['csp ' , 'cspReportOnly ' ] as $ key ) {
9694 if (empty ($ config [$ key ])) {
9795 continue ;
9896 }
9997 $ value = self ::buildPolicy ($ config [$ key ]);
10098 if (strpos ($ value , "'nonce' " )) {
101- $ code [0 ] = '$cspNonce = base64_encode(random_bytes(16)); ' ;
10299 $ value = Nette \DI \ContainerBuilder::literal (
103- 'str_replace(?, ? . $cspNonce, ?) ' ,
100+ 'str_replace(?, ? . (isset( $cspNonce) \? $cspNonce : $cspNonce = base64_encode(random_bytes(16))) , ?) ' ,
104101 ["'nonce " , "'nonce- " , $ value ]
105102 );
106103 }
@@ -111,16 +108,15 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
111108 $ headers ['Feature-Policy ' ] = self ::buildPolicy ($ config ['featurePolicy ' ]);
112109 }
113110
114- $ code [] = Helpers::formatArgs ('$response = $this->getService(?); ' , [$ this ->prefix ('response ' )]);
115111 foreach ($ headers as $ key => $ value ) {
116112 if ($ value !== '' ) {
117- $ code [] = Helpers::formatArgs ('$response->setHeader(?, ?); ' , [$ key , $ value ]);
113+ $ builder ->getDefinition ($ this ->prefix ('response ' ))
114+ ->addSetup ('?->setHeader(?, ?); ' , ['@self ' , $ key , $ value ]);
118115 }
119116 }
120117
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})(); " );
118+ $ builder ->getDefinition ($ this ->prefix ('response ' ))
119+ ->addSetup ('?->setCookie(...?) ' , ['@self ' , ['nette-samesite ' , '1 ' , 0 , '/ ' , null , null , true , 'Strict ' ]]);
124120 }
125121
126122
0 commit comments