1010namespace Nette \Bridges \HttpDI ;
1111
1212use Nette ;
13- use Nette \PhpGenerator \Helpers ;
14-
1513
1614/**
1715 * HTTP extension for Nette DI.
@@ -71,13 +69,13 @@ public function loadConfiguration()
7169 }
7270
7371
74- public function afterCompile ( Nette \ PhpGenerator \ ClassType $ class )
72+ public function beforeCompile ( )
7573 {
7674 if ($ this ->cliMode ) {
7775 return ;
7876 }
7977
80- $ initialize = $ class -> getMethod ( ' initialize ' );
78+ $ builder = $ this -> getContainerBuilder ( );
8179 $ config = $ this ->getConfig ();
8280 $ headers = array_map ('strval ' , $ config ['headers ' ]);
8381
@@ -91,16 +89,14 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
9189 $ headers ['X-Frame-Options ' ] = $ frames ;
9290 }
9391
94- $ code = [];
9592 foreach (['csp ' , 'cspReportOnly ' ] as $ key ) {
9693 if (empty ($ config [$ key ])) {
9794 continue ;
9895 }
9996 $ value = self ::buildPolicy ($ config [$ key ]);
10097 if (strpos ($ value , "'nonce' " )) {
101- $ code [0 ] = '$cspNonce = base64_encode(random_bytes(16)); ' ;
10298 $ value = Nette \DI \ContainerBuilder::literal (
103- 'str_replace(?, ? . $cspNonce, ?) ' ,
99+ 'str_replace(?, ? . (isset( $cspNonce) \? $cspNonce : $cspNonce = base64_encode(random_bytes(16))) , ?) ' ,
104100 ["'nonce " , "'nonce- " , $ value ]
105101 );
106102 }
@@ -111,16 +107,15 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
111107 $ headers ['Feature-Policy ' ] = self ::buildPolicy ($ config ['featurePolicy ' ]);
112108 }
113109
114- $ code [] = Helpers::formatArgs ('$response = $this->getService(?); ' , [$ this ->prefix ('response ' )]);
115110 foreach ($ headers as $ key => $ value ) {
116111 if ($ value !== '' ) {
117- $ code [] = Helpers::formatArgs ('$response->setHeader(?, ?); ' , [$ key , $ value ]);
112+ $ builder ->getDefinition ($ this ->prefix ('response ' ))
113+ ->addSetup ('?->setHeader(?, ?); ' , ['@self ' , $ key , $ value ]);
118114 }
119115 }
120116
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})(); " );
117+ $ builder ->getDefinition ($ this ->prefix ('response ' ))
118+ ->addSetup ('?->setCookie(...?) ' , ['@self ' , ['nette-samesite ' , '1 ' , 0 , '/ ' , null , null , true , 'Strict ' ]]);
124119 }
125120
126121
0 commit comments