1010namespace Nette \Bridges \HttpDI ;
1111
1212use Nette ;
13- use Nette \PhpGenerator \Helpers ;
1413
1514
1615/**
@@ -71,13 +70,9 @@ public function loadConfiguration()
7170 }
7271
7372
74- public function afterCompile ( Nette \ PhpGenerator \ ClassType $ class )
73+ public function beforeCompile ( )
7574 {
76- if ($ this ->cliMode ) {
77- return ;
78- }
79-
80- $ initialize = $ class ->getMethod ('initialize ' );
75+ $ builder = $ this ->getContainerBuilder ();
8176 $ config = $ this ->getConfig ();
8277 $ headers = array_map ('strval ' , $ config ['headers ' ]);
8378
@@ -91,16 +86,14 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
9186 $ headers ['X-Frame-Options ' ] = $ frames ;
9287 }
9388
94- $ code = [];
9589 foreach (['csp ' , 'cspReportOnly ' ] as $ key ) {
9690 if (empty ($ config [$ key ])) {
9791 continue ;
9892 }
9993 $ value = self ::buildPolicy ($ config [$ key ]);
10094 if (strpos ($ value , "'nonce' " )) {
101- $ code [0 ] = '$cspNonce = base64_encode(random_bytes(16)); ' ;
10295 $ value = Nette \DI \ContainerBuilder::literal (
103- 'str_replace(?, ? . $cspNonce, ?) ' ,
96+ 'str_replace(?, ? . (isset( $cspNonce) \? $cspNonce : $cspNonce = base64_encode(random_bytes(16))) , ?) ' ,
10497 ["'nonce " , "'nonce- " , $ value ]
10598 );
10699 }
@@ -111,16 +104,15 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
111104 $ headers ['Feature-Policy ' ] = self ::buildPolicy ($ config ['featurePolicy ' ]);
112105 }
113106
114- $ code [] = Helpers::formatArgs ('$response = $this->getService(?); ' , [$ this ->prefix ('response ' )]);
115107 foreach ($ headers as $ key => $ value ) {
116108 if ($ value !== '' ) {
117- $ code [] = Helpers::formatArgs ('$response->setHeader(?, ?); ' , [$ key , $ value ]);
109+ $ builder ->getDefinition ($ this ->prefix ('response ' ))
110+ ->addSetup ('?->setHeader(?, ?); ' , ['@self ' , $ key , $ value ]);
118111 }
119112 }
120113
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})(); " );
114+ $ builder ->getDefinition ($ this ->prefix ('response ' ))
115+ ->addSetup ('?->setCookie(...?) ' , ['@self ' , ['nette-samesite ' , '1 ' , 0 , '/ ' , null , null , true , 'Strict ' ]]);
124116 }
125117
126118
0 commit comments