44
55use GuzzleHttp \Client ;
66use Illuminate \Http \Client \Request ;
7+ use Illuminate \Support \Arr ;
78use Illuminate \Support \Facades \File ;
9+ use Illuminate \Support \Facades \Hash ;
810use Illuminate \Support \Facades \Http ;
911use Illuminate \Support \Str ;
1012
@@ -37,6 +39,9 @@ class HttpRecorder
3739
3840 private $ usePrettyJson = true ;
3941
42+ private $ requestNames = [];
43+
44+
4045 public function storeIn ($ directory )
4146 {
4247 $ this ->snapshotDirectory = $ directory ;
@@ -51,22 +56,33 @@ public function minifyJson()
5156 return $ this ;
5257 }
5358
59+ public function nameForNextRequest ($ name )
60+ {
61+ array_push ($ this ->requestNames , $ name );
62+ }
63+
5464 public function handle (Request $ request )
5565 {
5666 $ forceRecording = in_array ('--force-recording ' , $ _SERVER ['argv ' ]);
5767
5868 $ urlInfo = parse_url ($ request ->url ());
69+ $ payload = null ;
5970
6071 // create specific filename for storing snapshots
72+ $ header = $ request ->headers ();
6173 $ method = Str::lower ($ request ->method ());
6274 $ name = Str::slug (Str::replace ('/ ' , '- ' , $ urlInfo ['path ' ]));
63- $ query = Str::slug (Str::replace ('& ' , '_ ' , Str::replace ('= ' , '- ' , $ urlInfo ['query ' ])));
75+ $ payload = ($ method === 'get ' ) ? $ urlInfo ['query ' ] : $ request ->body ();
76+ $ queryName = array_pop ($ this ->requestNames ) ?? hash ('adler32 ' , $ payload );
6477
65- $ fileName = "{$ method }_ {$ name }_ {$ query }.json " ;
78+ $ fileName = "{$ method }_ {$ name }_ {$ queryName }.json " ;
6679 $ directoryPath = "tests/ {$ this ->snapshotDirectory }" ;
6780 $ filePath = "{$ directoryPath }/ {$ fileName }" ;
6881
69- if ($ forceRecording || ! File::exists ($ filePath )) {
82+ // filter out Notion API Token Header
83+ $ header = Arr::except ($ header , ['Authorization ' ]);
84+
85+ if ($ forceRecording || !File::exists ($ filePath )) {
7086 File::makeDirectory ($ directoryPath , 0744 , true , true );
7187
7288 $ client = new Client ();
@@ -77,7 +93,10 @@ public function handle(Request $request)
7793 ]);
7894
7995 $ recordedResponse = [
96+ 'header ' => $ header ,
97+ 'method ' => $ method ,
8098 'status ' => $ response ->getStatusCode (),
99+ 'payload ' => ($ method === 'get ' ) ? $ payload : json_decode ($ payload , true ),
81100 'data ' => json_decode ($ response ->getBody ()->getContents (), true ),
82101 ];
83102
0 commit comments