@@ -34,6 +34,13 @@ final class RouteRegister
3434
3535 private $ _middleware = [];
3636
37+ /**
38+ * Instance of rest request
39+ *
40+ * @var WP_REST_Response
41+ */
42+ private $ _restResponse ;
43+
3744 /**
3845 * Instance of rest request
3946 *
@@ -314,7 +321,10 @@ public function handleRequest()
314321
315322 $ this ->handleMiddleware ();
316323 $ this ->handleAction ($ this );
317- ob_clean ();
324+
325+ if (ob_get_level ()) {
326+ ob_clean ();
327+ }
318328
319329 return $ this ->sendResponse ();
320330 }
@@ -365,6 +375,7 @@ private function authorize()
365375 ->code ('NOT_AUTHORIZED ' )
366376 ->message ($ message )
367377 );
378+
368379 $ this ->sendResponse ();
369380 }
370381 }
@@ -459,6 +470,11 @@ private function invokeAsReflection($class, $method, $params = [])
459470 $ requestParams [] = $ this ->getParamValue ($ param );
460471 }
461472
473+ if (wp_is_serving_rest_request () && isset ($ this ->_restResponse )) {
474+ // maybe failed at middleware,authorization or validation
475+
476+ return Response::instance ();
477+ }
462478 $ params = array_merge ($ requestParams , $ params );
463479
464480 return $ reflectionMethod ->invoke ($ reflectionMethod ->isStatic () ? null : new $ class (), ...$ params );
@@ -515,6 +531,8 @@ private function sendApiResponse()
515531 $ restResponse ->set_status ($ this ->_response ['http_status ' ]);
516532 $ restResponse ->set_headers ($ this ->_response ['headers ' ]);
517533
534+ $ this ->_restResponse = $ restResponse ; // will USE this to return before middleware or action excutes
535+
518536 return $ restResponse ;
519537 }
520538
0 commit comments