@@ -71,6 +71,7 @@ public static function findParentDirContainingFile(string $filename): string {
7171 public function sendRequest (string $ verb , string $ url , $ body = null , array $ headers = [], array $ options = []): void {
7272 parent ::sendRequest ($ verb , $ url , $ body , $ headers , $ options );
7373 $ lastRequest = $ this ->getLastRequest ();
74+ $ parsedInput = $ this ->getParsedInputFromRequest ($ lastRequest );
7475
7576 // Verb
7677 Assert::assertEquals ($ verb , $ lastRequest ->getRequestMethod ());
@@ -88,8 +89,37 @@ public function sendRequest(string $verb, string $url, $body = null, array $head
8889
8990 // Form params
9091 if (array_key_exists ('form_params ' , $ this ->requestOptions )) {
91- Assert::assertEquals ($ this ->requestOptions ['form_params ' ], $ lastRequest -> getParsedInput () );
92+ Assert::assertEquals ($ this ->requestOptions ['form_params ' ], $ parsedInput );
9293 }
94+
95+ // JSON payload
96+ if (array_key_exists ('json ' , $ this ->requestOptions )) {
97+ Assert::assertEquals ($ this ->requestOptions ['json ' ], $ parsedInput );
98+ }
99+ }
100+
101+ private function getParsedInputFromRequest (RequestInfo $ requestInfo ): array {
102+ $ headers = $ requestInfo ->getHeaders ();
103+ $ contentType = $ headers ['Content-Type ' ] ?? $ headers ['CONTENT_TYPE ' ] ?? '' ;
104+ $ input = $ requestInfo ->getInput ();
105+ if (str_contains ((string )$ contentType , 'application/json ' ) || $ this ->isJson ($ input )) {
106+ $ decoded = json_decode ($ input , true );
107+ if (is_array ($ decoded )) {
108+ return $ decoded ;
109+ }
110+ }
111+
112+ return $ requestInfo ->getParsedInput () ?? [];
113+ }
114+
115+ private function hasNestedPayload (array $ payload ): bool {
116+ foreach ($ payload as $ value ) {
117+ if (is_array ($ value ) || $ value instanceof \stdClass) {
118+ return true ;
119+ }
120+ }
121+
122+ return false ;
93123 }
94124
95125 #[Given('set the response to: ' )]
@@ -106,12 +136,12 @@ public function setTheResponseTo(PyStringNode $response): void {
106136 #[\Override]
107137 public function theResponseShouldBeAJsonArrayWithTheFollowingMandatoryValues (TableNode $ table ): void {
108138 $ lastRequest = $ this ->getLastRequest ();
109- $ body = json_encode ( $ lastRequest -> getParsedInput () );
110- Assert:: assertIsString ( $ body );
111- // Mock response to be equal to body of request
112- $ this -> mockServer -> setDefaultResponse ( new MockWebServerResponse (
113- $ body
114- ));
139+ $ parsedInput = $ this -> getParsedInputFromRequest ( $ lastRequest );
140+ if ( $ this -> hasNestedPayload ( $ parsedInput )) {
141+ $ body = json_encode ( $ parsedInput );
142+ Assert:: assertIsString ( $ body );
143+ $ this -> response = new Response ( 200 , [], $ body);
144+ }
115145 parent ::theResponseShouldBeAJsonArrayWithTheFollowingMandatoryValues ($ table );
116146 }
117147}
0 commit comments